bash: test if $WORD is in set
This is a Bash-only (>= version 3) solution that uses regular expressions:
if [[ "$WORD" =~ ^(cat|dog|horse)$ ]]; then echo "$WORD is in the list" else echo "$WORD is not in the list" fi
If your word list is long, you can store it in a file (one word per line) and do this:
if [[ "$WORD" =~ $(echo ^\($(paste -sd'|' /your/file)\)$) ]]; then echo "$WORD is in the list" else echo "$WORD is not in the list" fi
One caveat with the file approach:
It will break if the file has whitespace. This can be remedied by something like:
sed 's/[[:blank:]]//g' /your/file | paste -sd '|' /dev/stdin
Thanks to @terdon for reminding me to properly anchor the pattern with
And `shopt -s nocasematch` might help if you want the search to be case insensitive.
Note that you have to use ```[[``` and ```]]``` - ```[``` and ```]``` are not enough.