Here I found nice solution to test if variable is a number:
case $string in
''|*[!0-9]*) echo bad ;;
*) echo good ;;
esac
I'm trying to modify it to test if variable is a 1,2,3 or 4-digit natural number (within a range 0-9999), so I added |*[0-9]{5,}*
to exclude numbers with more than 5 digits, but the code below prints good
for numbers greater then 9999 e.g. 1234567.
case $string in
''|*[!0-9]*|*[0-9]{5,}*) echo bad ;;
*) echo good ;;
esac
I'm using ash from busybox.
Not sure if you need this in a case statement, since I would just do:
if { test "$string" -ge 0 && test "$string" -lt 10000; } 2> /dev/null; then
echo good
else
echo bad
fi
If you want to use a case statement in a strictly portable shell, you're probably stuck with:
case $string in
[0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9]) echo good;;
*) echo bad;;
esac