bashconditional-statementslogical-operators

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


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!


Solution

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