checking for numerical argument

checking for numerical argument

Post by gyromagnet » Sat, 21 Jul 2001 01:45:41



Hi,
Iam looking for a method to assure that an argument passed to my shell
script is a number. I am using the Bourne shell and have created the
following function:

is_a_number()
{
        num=`echo "$1 + 0" | bc`
        if [ "$num" = "$1" ]; then
                echo "TRUE"
        else
                echo "FALSE"
        fi

Quote:}

Is there a better or standard way to do this?

Thanks.

 
 
 

checking for numerical argument

Post by Willia » Tue, 24 Jul 2001 00:35:27



Quote:> Hi,
> Iam looking for a method to assure that an argument passed to my shell
> script is a number. I am using the Bourne shell and have created the
> following function:

> is_a_number()
> {
>         num=`echo "$1 + 0" | bc`
>         if [ "$num" = "$1" ]; then
>                 echo "TRUE"
>         else
>                 echo "FALSE"
>         fi
> }

What happens if the user enters "001"?

Here's what I've been using:
    if [ -n "$1" -a `expr \$1: .*\[\^0-9\].*` -eq 0 ] ; then
        echo "TRUE"
    else
        echo "FALSE"
    fi

-Wm