user137369
user137369

Reputation: 5705

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.

Upvotes: 1

Views: 176

Answers (1)

rici
rici

Reputation: 241771

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.

Upvotes: 5

Related Questions