price=\"1.11\"
case $price in
\'\'|*[!0-9]*) echo \"It is not an integer.\";
;;
esac
Output: It is not an integer
Doing this in a POSIX-compatible way is tricky; your current pattern matches non-integers. Two bash
extensions make this fairly easy:
Use extended patterns
shopt -s extglob
case $price in
# +([0-9]) - match one or more integer digits
# ?(.+([0-9])) - match an optional dot followed by zero or more digits
+([0-9]))?(.*([0-9]))) echo "It is an integer" ;;
*) echo "Not an integer"
esac
Use a regular expression
if [[ $price =~ ^[0-9]+(.?[0-9]*)$ ]]; then
echo "It is an integer"
else
echo "Not an integer"
fi
(In theory, you should be able to use the POSIX command expr
to do regular expression matching as well; I'm having trouble getting it to work, and you haven't specified POSIX compatibility as a requirement, so I'm not going to worry about it. POSIX pattern matching isn't powerful enough to match arbitrarily long strings of digits.)
If you only want to match a "decimalized" integer, rather than arbitrary floating point values, it is of course simpler:
+([0-9])?(.)
[0-9]+\.?
Try this regular expression ^(0*[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*)$