bashif-statement

Check if variable is different from any of many options


If I have the code

if [[ this != that && this != another ]]

Is there a way to make it sorter? Something like

if [[ this !=that && != another ]]

Naturally that won’t work, but something like that, that can shorten the conditions.


Solution

  • With bash, you can use regular expressions inside [[:

    if [[ ! this =~ ^(that|another|this\ one)$ ]]; then
       # do something
    fi
    

    The precedence of the ! (not) operator might be confusing if you're used to any other programming language. Also, beware: do not put the regular expression in quotes. If you do, it is no longer a regular expression.