An alternative POSIX solution:
if printf '%s' "$num" | grep -xE '(9|75|200)' >/dev/null; then
echo "do this"
elif printf '%s' "$num" | grep -xE '(40|53|63)' >/dev/null; then
echo "do something for this"
else
echo "for other do this"
fi
This is awfully slow ~50 times slower than the case
option.
This is a shorter and I believe a simpler script, only twice the time of the case option:
#!/bin/sh
num="$1" a='9 75 200' b='40 53 63'
tnum() {
for arg
do [ "$arg" = "$num" ] && return 0
done return 1
}
if tnum $a; then
echo "do this"
elif tnum $b; then
echo "do something for this"
else
echo "for other do this"
fi
CAVEAT: No test [ "$arg" = "$num" ]
will work in all cases, this fails on 00 = 0
for example.
And a numerical test [ "$arg" -eq "$num" ]
will fail to match empty values [ "" -eq "" ]
.
You may choose what works better in your case.
-eq
test would succeed? How does-eq
handle something like9.0
? – Wildcard Mar 06 '16 at 09:04case
is just doing string compare whereas-eq
is doing an arithmetic compare, so the former will fail for num=010 compared with 10, whereas the latter will compare equal. Only integers are allowed though. – meuh Mar 06 '16 at 09:11case
: http://unix.stackexchange.com/questions/89712/bash-float-to-integer – Murphy Mar 06 '16 at 11:06sh
/[
implementation, see How can I check that two input values are correct in a bash script? – Stéphane Chazelas Mar 06 '16 at 12:49