How to check if variable is integer (avoid problem with spaces around) in POSIX shell script?
#!/bin/sh
is_integer ()
{
case "${1#[+-]}" in
(*[!0123456789]*) return 1 ;;
('') return 1 ;;
(*) return 0 ;;
esac
}
Uses only POSIX builtins.
It is not clear from the spec if +1
is supposed to be an integer, if not then remove the +
from the case
line.
It works as follows. the ${1#[+-]}
removes the optional leading sign. If you are left with something containing a non digit then it is not an integer, likewise if you are left with nothing. If it is not not an integer then it is an integer.
Edit: change ^ to ! to negate the character class - thanks @LinuxSecurityFreak