Checking if a variable is a number in ksh

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.

The Conversation

Follow the reactions below and share your own thoughts.

5 Responses to “Checking if a variable is a number in ksh”

  1. October 03, 2008 at 8:45 am, nacho_a said:

    What if $1 is 0?
    You’ll get FALSE!

    From expr’s man page:

    EXIT STATUS
    [...]
    0 if the expression is neither NULL nor 0
    1 if the expression is either NULL or 0

    [...]
    I’d use “-eq 2″ instead of “-ne 0.”

    Thanks anyway, good tip.

    Reply

    • January 09, 2009 at 5:31 pm, Mr. KIPS said:

      I wouldn’t play with the exit status. Instead, change the arithmetic expression. Use expr $1 +1.

      Reply

  2. April 15, 2009 at 7:28 pm, Andrew said:

    I’m not sure if anyone will read this, but to check if a variable is a number in ksh, it would take 1 expression, there is no reason to add, subtract or do any arithmetic. Example of a script:

    G_VAR=$1
    if [[ $G_VAR = +([0-9]) ]]; then
    print “G_VAR is a number”
    else
    print “G_VAR is not a number”
    fi

    Reply

    • July 16, 2010 at 3:00 pm, murph said:

      Perfect.

      Reply

  3. July 20, 2011 at 2:28 am, Virtual_path said:

    Works Great.
    Thanks

    Reply

Leave a Reply