Shell – How to simplify a conditional with multiple or statements

shell-script

I am writing a shell script that checks to see if a parameter matches a string. There are around 20 of them and more may need to be added in the future.

Currently the way I have it written it's hard to read and would be cumbersome to update. I'm not very familiar with shell scripting so I'm not sure of the best way to simplify this and make it easier to manage.

if [ $4 =="CRITICAL" ] && [[ $2 == "foo" || $2 == "bar" || $2 == "foo" || $2 == "bar" || $2 == "foo" || $2 == "bar" || $2 == "foo" || $2 == "bar" || $2 == "foo" || $2 == "bar" || ]]
  VARIABLE=1
fi

Foo and bar would all be different strings in the above script.

Best Answer

if [[ $4 == CRITICAL && $2 =~ ^(a|b|c|d|e|f|g)$ ]]; then
  VARIABLE=1
fi

BTW, unquoted variables and positional parameters are safe to use inside [[ ... ]], but not in [ ... ]. In other words, your [ $4 == "CRITICAL" ] should be [ "$4" == "CRITICAL" ].

Also, CRITICAL doesn't need to be quoted at all above . It's a fixed string, with no spaces or shell metacharacters. If it was a fixed string that did need quoting for any reason, it's best to use single quotes.

Single quotes are for fixed strings, double-quotes are for when you want to interpolate variables, command substitutions, etc into a string.

Related Question