7

I just started doing shell scripts and getting unknown operand error while using regex in if statement. i searched google but did not get anything

IP="172.21.1.1"
if [[ "$IP" =~ /d ]] ; then
echo "qqq"
fi

Getting error as

sh: =~: unknown operand

Bash version is : BusyBox v1.19.3 (2012-01-31 08:57:52 PST) built-in shell (ash)

Sumit
  • 1,953
  • 6
  • 32
  • 58
  • 3
    Looks like you’re trying to run a Bash script with sh (but it’s odd that it doesn’t complain about `[[`). How do you run it, and what’s the shebang? – Biffen May 24 '18 at 12:07
  • I am typing these commands on bash terminal. There is no shebang. I just written these lines on the terminal and getting error – Sumit May 24 '18 at 12:08
  • What’s the output of `echo $SHELL $BASH_VERSION`? – Biffen May 24 '18 at 12:09
  • /bin/bash is the output – Sumit May 24 '18 at 12:11
  • That’s odd. What about `bash --version`? – Biffen May 24 '18 at 12:11
  • BusyBox v1.19.3 (2012-01-31 08:57:52 PST) built-in shell (ash) – Sumit May 24 '18 at 12:12
  • 1
    So `/bin/bash` is ash, and I’m guessing that’s the cause of the problem. Looks like a wonky setup. – Biffen May 24 '18 at 12:13
  • This is what I am having. How to solve the issue on my setup – Sumit May 24 '18 at 12:14
  • Install Bash…? Use something that works with ash…? – Biffen May 24 '18 at 12:15
  • 1
    Busybox doesn't support "advanced" features for any of the software it includes and I believe you'd have to build your own version of BB to incorporate a real bash. @Nitesh , you'll have to keep with the bare minimum of shell features. Reading about the original Bourne shell will show you what sort of logic tools are available, and it won't include `/d` type reg-ex., you'd have to specify that as `[0-9]` ) . You may discover that `ash` has even fewer features than `sh`. Good luck. – shellter May 24 '18 at 12:25
  • 1
    @Nitesh: This could be useful - https://stackoverflow.com/questions/21010882/how-to-match-regexp-with-ash – Inian May 24 '18 at 12:25

1 Answers1

8

This is happening because the operator =~ doesn't existe for bash.

As see you are trying to use a Regex to compare your variables. I recommend to use the expr command. Here is an example:

IP="172.21.1.1"
if [[ $(expr match "$IP" 'my_regex') != 0 ]]; then echo "qqq"; fi;
Nestor Vanz
  • 119
  • 1
  • 4
  • This worked for me! This `expr` command returns the number of matching letters, so it lets you build more complex conditionals. – Alejandro S. Nov 05 '20 at 10:38
  • 1
    bash certainly does have the `=~` operator (starting in [version 3.0-alpha](https://wiki.bash-hackers.org/scripting/bashchanges#conditional_expressions_and_test_command)); the problem here is that the shell isn't actually bash, it's ash. – Gordon Davisson Aug 23 '21 at 18:39
  • This fixes my script. Thanks man. – devxvda1 Feb 17 '22 at 15:35