Simple regexes can allow non-numbers such as "11--22--99" (although they do evaluate mathematically inside the (())
).
The following regex only allows 0 or negative integers without leading zeros and rejects negative zero.
for a in 0 -0 00 -1 -01 1 1-1 --1
do
if [[ $a =~ ^(-[1-9][0-9]*|0)$ ]]
then
echo "[+] $a passes"
else
echo "[X] $a doesn't"
fi
done
Output:
[+] 0 passes
[X] -0 doesn't
[X] 00 doesn't
[+] -1 passes
[X] -01 doesn't
[X] 1 doesn't
[X] 1-1 doesn't
[X] --1 doesn't
At this point, you don't really need to add a test for ((a <= 0))
although you could test whether it was less than or equal to some smaller number.
Edit:
You could put the integer validation test in a function and do the comparison separately for readability like this:
isint () {
[[ $1 =~ ^(-?[1-9][0-9]*|0)$ ]] # use [+-]? instead of -? to allow "+"
}
if isint "$var" && ((var <= 0))
then
echo "validated and compared: $var"
else
echo "non-integer or out of range: $var"
fi