29

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!

1
  • I reopened this since NONE of the answers in the other post that's supposed to have already provided the answer to this question even mentioned being able to use parentheses inside [[ ]]. Please review the question and the wanted answers properly first. Commented Feb 15 at 16:41

1 Answer 1

52
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.