I want to check to see whether a word is in a list (or an element is a member of a set).
The safest way to do this would be to loop over all elements in your set/list and check them for the element/word you are looking for. Say we are looking for the content of bar in the array foo:
for element in "${foo[@]}"; do [[ $element = $bar ]] && echo "Found $bar." done
Or, to stop searching when you find it:
for element in "${foo[@]}"; do [[ $element = $bar ]] && { echo "Found $bar."; break; } done
If for some reason your list/set is not in an array, but is a string of words, and the element you are searching for is also a word, you can use this:
for element in $foo; do [[ $element = $bar ]] && echo "Found $bar." done
A less safe, but more clever version:
if [[ " $foo " = *\ "$bar"\ * ]]; then echo "Found $bar." fi
And, if for some reason you don't know the syntax of for well enough, here's how to check your script's parameters for an element. For example, '-v':
for element; do [[ $element = '-v' ]] && echo "Switching to verbose mode." done
GNU's grep has a \b feature which allegedly matches the edges of words. Using that, one may attempt to replicate the "clever" approach used above, but it is fraught with peril:
# Is 'foo' one of the positional parameters? egrep '\bfoo\b' <<<"$@" >/dev/null && echo yes # This is where it fails: is '-v' one of the positional parameters? egrep '\b-v\b' <<<"$@" >/dev/null && echo yes # Unfortunately, \b sees "v" as a separate word. # Nobody knows what the hell it's doing with the "-". # Is "someword" in the array 'array'? egrep '\bsomeword\b' <<<"${array[@]}" # Obviously, you can't use this if someword is '-v'!
Since this "feature" of GNU grep is both non-portable and poorly defined, we don't recommend using it.