Linux shell scripting - testing for numeric argument

I've been tinkering on the problem of checking if an argument is numeric or not inside shell scripts for quite a time already. I searched the internet for a way to test if a variable in a bash script is consisting only of digits but haven't found a clear solution yet. Either that or I'm unable to bring up the right search terms. The main problem is that it has to be cross-Unix-compatible (Linux, Solaris, AIX).

A few weeks ago I completed an in-corporate eLearning course about Unix Shell Scripting. This course also contained lessons about basic Unix commands like sed and awk.

Today this tiny problem struck at me again and I tried to bring in my new knowledge from the course. What I came up with is:


# check first argument

# test if argument present, then compare original string to the string without non-digit characters
# if string is the same, it only consist of digits
if [ ! -z "$number" -a "$number" = "$(echo $number | sed 's/[^[:digit:]]//g')" ]
 echo "Argument is full numeric"
 echo "Argument is not full numeric"

I tested it and it seems to work on all the platforms I need it. I don't like the inline call of sed but for the sake of compatibility I'll settle with that.

Perhaps I'll find an easier solution in the future but now that's not a priority anymore...


Similar entries