bash: test if $WORD is in set
case $word in
dog|cat|horse) echo yes;;
*) echo no;;
esac
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 $
.
How about:
#!/usr/bin/env bash
WORD="$1"
for w in dog cat horse
do
if [ "$w" == "$WORD" ]
then
yes=1
break
fi
done;
[ "$yes" == "1" ] && echo "$WORD is in the list" ||
echo "$WORD is not in the list"
Then:
$ a.sh cat
cat is in the list
$ a.sh bob
bob is not in the list