Checking if a variable is a number in ksh

Posted October 25, 2004 by u02sgb in 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.
#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
expr $1 + 0 >/dev/null 2>&1
if [ $? -ne 0 ]
echo "FALSE"
echo "TRUE"

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" ]]
head -${END} ${1}| tail +${START}
echo "Entered values invalid START: ${START} END: ${END}"

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

The Conversation

Follow the reactions below and share your own thoughts.