Bash Tips & Tricks: Checking a variable against multiple values
Sometimes we need to check a variable against a list of possible values. We usually would do in Bash what we do in other languages:
if [[ "$field" == "name" || "$field" == "address" || "$field" == "city" … ]]; then
# Do something
fi
We might even try something like this:
case "$field" in
name|address|city) do_something ;;
*) ;;
esac
But there’s another way of doing the if block, if you’re willing to move things around a bit:
if [[ " name address city " == *" $field "* ]]; then
# Do something
fi
It’s also very useful for checking if a particular value is contained in an array, for example if it’s some list of values retrieved from an API:
fields=(name address city)
if [[ " ${fields[*]} " == *" $field "* ]]; then
# Do something
fi
The key here are the spaces around the entire list. If your value has spaces in
it, you can use whatever character you want as a delimiter as long as none of
the possible values contain it, although this doesn’t apply as easily to arrays.
There’s always a way around, however, using printf
to add the delimiters:
fields=('zip code' 'home phone' 'mobile phone')
if [[ "|$(printf -- '%s|' "${fields[@]}")" == *"|${field}|"* ]]; then
# Do something
fi
Maybe not as pretty and requires spawning a subshell, but it’s a very straightforward approach.