You could use a case
statement in an if
test, but the code would look a bit hairy:
if case "$1" in (cat|dog|mouse) true ;; (*) false; esac; then
printf '"%s" is one of cat, dog or mouse\n' "$1"
else
printf '"%s" is unknown\n' "$1"
fi
or slightly shorter,
if ! case "$1" in (cat|dog|mouse) false; esac; then
printf '"%s" is one of cat, dog or mouse\n' "$1"
else
printf '"%s" is unknown\n' "$1"
fi
This is using an case
clause just to do the pattern matching for the if
clause. It introduces an unnecessary true/false test.
It's better to just use case
:
case "$1" in
cat|dog|mouse)
printf '"%s" is one of cat, dog or mouse\n' "$1"
;;
*)
printf '"%s" is unknown\n' "$1"
esac
Don't do this:
is_one_of () {
eval "case $1 in ($2) return 0; esac"
return 1
}
if is_one_of "$1" 'cat|dog|mouse'; then
printf '"%s" is one of cat, dog or mouse\n' "$1"
else
printf '"%s" is unknown\n' "$1"
fi
or this:
is_one_of () (
word=$1
shift
IFS='|'
eval "case $word in ($*) return 0; esac"
return 1
)
if is_one_of "$1" cat dog mouse; then
printf '"%s" is one of cat, dog or mouse\n' "$1"
else
printf '"%s" is unknown\n' "$1"
fi
... because you're just adding more dangerous cruft, just to be able to use an if
statement in your code in place of a perfectly reasonable case
statement.
=~
isn't valid inside the POSIX single-bracket test – steeldriver Jun 02 '18 at 02:29[
is POSIX, but[[
is extended feature of bash, ksh ( apparently it's originated from there, and zsh.case
example is most POSIX of all, though – Sergiy Kolodyazhnyy Jun 02 '18 at 02:55case "$1" in
does not need to be quoted, no word splitting nor pathname expansion are performed in that token. – Jun 02 '18 at 10:58