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!
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 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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With