Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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"

Getting error as

sh: =~: unknown operand

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

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, 2018 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, 2018 at 12:08 So /bin/bash is ash, and I’m guessing that’s the cause of the problem. Looks like a wonky setup. 😖 – Biffen May 24, 2018 at 12:13 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, 2018 at 12:25

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;
                This worked for me! This expr command returns the number of matching letters, so it lets you build more complex conditionals.
– Alejandro S.
                Nov 5, 2020 at 10:38
                bash certainly does have the =~ operator (starting in version 3.0-alpha); the problem here is that the shell isn't actually bash, it's ash.
– Gordon Davisson
                Aug 23, 2021 at 18:39
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.