I just had the same problem and found a surprisingly understandable solution which does not require any regex knowledge.
This works in Bash and ksh, and in zsh with setopt kshglob
:
WORD=abc
[[ "$WORD" == @(def|abc|ghi|foo|barbaz) ]] && echo Word is in set.
(Native zsh version would be the same without the @
sign).
How does this work? I don't want to repeat large portions of the bash manual here, but in my own words:
If the binary operator ==
is used with the compound command [[
, the word to the right side of the operator undergoes pattern matching as explained in the section "Pattern Matching" in the bash manual. Furthermore, under these conditions, while matching, the shell option extglob
is assumed to be set (regardless of the actual setting); this is the key point in understanding the above.
But what if the words in your set already contain characters which have a special meaning in pattern matching, command substitution and other expansions? The remedy is easy: Just use something like
[[ "$WORD" == @('a*'|abc|'?ghi'|'$DontExpandMe'|barbaz) ]] && echo Word is in set.
I found this to be a very easy, understandable and efficient (as long as $WORD
is short) solution which does not have side effects or is dangerous like the set
-based methods.