Click to See Complete Forum and Search --> : Bash script: How do I check if $1 is an integer?


Wallex
10-20-2002, 09:08 PM
$1 is supposed to go between 1 and 100, I can do the range check using the test function, but if I use a char or something non-numerical, it will bark back at me with a "[: a: integer expression expected" msg. I read the man for test and apparently there's no way to test if a var can be interpreted as a number. I've managed my own by doing a test which asks if the value is between 0 and 100 (otherwise includes nonnumerical values for $1) so, my script works. I just am annoyed that that error messages pops up... how can I 'catch' or hide that error message? Or how should I be asking 'in a safe way' that $1 is in the 0-100 range? Currently what I do is:
if [ $vol ]
then
if ! [ $vol -ge 0 ] || ! [ $vol -le 100 ]
then
echo $vol is an invalid value. Range is [0-100]
return 1
fi
fi

bwkaz
10-21-2002, 02:04 PM
Wow, that's odd. I would have figured it's easy enough to add to the "test" program, but apparently not.

Hmm... I'd be interested in finding out what to use for this as well.

uptimenotifier
10-21-2002, 06:46 PM
Try something like this:

if [ $vol ]
then
if [ ! $(echo "$vol" | grep -E "^[0-9]+$") ]
then
echo $vol is not a valid integer.
exit 1
else
if ! [ $vol -ge 0 ] || ! [ $vol -le 100 ]
then
echo $vol is an invalid value. Range is [0-100]
exit 1
fi
fi
fi

bwkaz
10-21-2002, 08:57 PM
Ah yes, duh, grep. I should have thought of that one! :p

Wallex
10-21-2002, 10:10 PM
The wonders of grep... thanks for the info!