Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use logical not operator in complex conditional expression in Bash? [duplicate]

I would like to have the logical not for the following condition expression in bash, how can I do this?

if [[ $var==2 || $var==30 || $var==50 ]] ; then
  do something
fi

how can I prepend the logical not directly in the above expression, it's very tedious to change it again into things like this:

if [[ $var!=2 && $var!=30 && $var==50 ]] ; then
  do something
fi

thanks for any hints!

like image 620
wiswit Avatar asked Sep 16 '13 14:09

wiswit


People also ask

Can I use != In bash?

Linux Bash scripting language provides the not equal “-ne” operator in order to compare two values if they are not equal. The not equal operator generally used with the if or elif statements to check not equal and execute some commands.

How do you negate a conditional statement in bash?

How to negate an if condition in a Bash if statement? (if not command or if not equal) To negate any condition, use the ! operator, for example: if ! <test-command>; then <command-on-failure>; fi .

How do I negate if condition in shell script?

NegationWhen we use the not operator outside the [[, then it will execute the expression(s) inside [[ and negate the result. If the value of num equals 0, the expression returns true. But it's negated since we have used the not operator outside the double square brackets.

How do you write multiple conditions in an if statement in Unix?

To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.


1 Answers

if ! [[ $var == 2 || $var == 30 || $var == 50 ]] ; then
  do something
fi

Or:

if [[ ! ($var == 2 || $var == 30 || $var == 50) ]] ; then
  do something
fi

And a good practice is to have spaces between your conditional operators and operands.

Some could also suggest that if you're just comparing numbers, use an arithmetic operator instead, or just use (( )):

if ! [[ var -eq 2 || var -eq 30 || var -eq 50 ]] ; then
  do something
fi

if ! (( var == 2 || var == 30 || var == 50 )) ; then
  do something
fi

Although it's not commendable or caution is to be given if $var could sometimes be not numeric or has no value or unset, since it could mean 0 as default or another value of another variable if it's a name of a variable.

like image 199
konsolebox Avatar answered Oct 19 '22 07:10

konsolebox