Checking if a variable is a number in ksh

Contributor Icon Contributed by u02sgb Date Icon October 25, 2004  
Tag Icon Tagged: Korn shell

Being able to test if a variable is a number in the Korn shell is very useful but not immediately obvious….


Due to shell programming not using any kind of type checking you can sometimes end up not knowing if a variable is a number or a string. The script below will return TRUE or FALSE depending on the parameter passed to it.
#!/bin/ksh
#Stuart Brock 24.09.04
#
#Usage is isanum
# e.g. isanum 4 -> TRUE
# isanum Not4 -> FALSE
#Will echo TRUE or FALSE depending on parameter
#
#Name Date Change
#—- —- ——
#SGB 24.09.04 Created
#
#Notes:
 
expr $1 + 0 >/dev/null 2>&1
if [ $? -ne 0 ]
then
echo “FALSE”
else
echo “TRUE”
fi

The code above works by adding zero to the variable using “expr” then checking it’s exit status. If $1 is a character expr will produce an error (non zero exit status).

I use this in my scripts in situations like checking an entered parameter is a number e.g.

if [[ `isanum ${START}` = "TRUE" && `isanum ${END}` = "TRUE" ]]
then
head -${END} ${1}| tail +${START}
else
echo “Entered values invalid START: ${START} END: ${END}”
fi

The isanum script obviously needs to be included in your PATH for this to work.

Previous recipe | Next recipe |
 

Viewing 1 Comment

 
close Reblog this comment
blog comments powered by Disqus