Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting sh: =~: unknown operand in shell scripting

Tags:

shell

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)

like image 879
Sumit Avatar asked May 24 '18 12:05

Sumit


People also ask

What are the basic operators in shell script?

Basic Operators in Shell Scripting. There are 5 basic operators in bash/shell scripting: Arithmetic Operators : These operators are used to perform normal arithmetics/mathematical operations. There are 7 arithmetic operators: Addition (+): Binary operation used to add two operands. Subtraction (-): Binary operation used to subtract two operands.

Why do I get an empty string error in shell script?

The error that you get comes from the fact that the script doesn't output anything, which means that the command substitution will be empty. Since it's unquoted, the command that the shell will try to execute will look like This is a syntax error. and the shell is not able to compare the empty string as an integer.

Why is my script not working in Linux?

The error that you get comes from the fact that the script doesn't output anything, which means that the command substitution will be empty. Since it's unquoted, the command that the shell will try to execute will look like

How do you read if statements in shell script?

You may read the if statement as "If the script did succeed". The error that you get comes from the fact that the script doesn't output anything, which means that the command substitution will be empty. Since it's unquoted, the command that the shell will try to execute will look like


1 Answers

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;
like image 66
Nestor Vanz Avatar answered Oct 01 '22 14:10

Nestor Vanz