I am trying to write a script in bash that check the validity of a user input.
I want to match the input (say variable x) to a list of valid values.
If the list is fixed in the script, I like the following the best:
validate() {
grep -F -q -x "$1" <
Then use validate "$x" to test if $x is allowed.
If you want a one-liner, and don't care about whitespace in item names, you can use this (notice -w instead of -x):
validate() { echo "11 22 33" | grep -F -q -w "$1"; }
Notes:
sh compliant.validate does not accept substrings (remove the -x option to grep if you want that).validate interprets its argument as a fixed string, not a regular
expression (remove the -F option to grep if you want that).Sample code to exercise the function:
for x in "item 1" "item2" "item 3" "3" "*"; do
echo -n "'$x' is "
validate "$x" && echo "valid" || echo "invalid"
done