I just can't figure out how do I make sure an argument passed to my script is a number or not.
All I want to do is something like this:
test *isnumber* $1 && VAR=$1 || echo "need a number"
One approach is to use a regular expression, like so:
re='^[0-9]+$' if ! [[ $yournumber =~ $re ]] ; then echo "error: Not a number" >&2; exit 1 fi
If the value is not necessarily an integer, consider amending the regex appropriately; for instance:
...or, to handle numbers with a sign:
Without bashisms (works even in the System V sh),
case $string in ''|*[!0-9]*) echo bad ;; *) echo good ;; esac
This rejects empty strings and strings containing non-digits, accepting everything else.
Negative or floating-point numbers need some additional work. An idea is to exclude
. in the first "bad" pattern and add more "bad" patterns containing the inappropriate uses of them (