Error handling

Hello fellow UNIX gurus :slight_smile:

I have a problem regarding the script below:

# Variables used in this shell.
power=0        # Stores squared integer
total=0        # Sum of all squared integers
num=0        # Stores command line arguements


# Provides error handling if command line arguments are 0.
if [ $# = 0 ]; then
    echo "Usage $0 - integer-list"
    exit 1
fi


# Function that is used to sum all integers values
# from the power variable; store the sum in total variable. 
sum()
{
    total=`expr $total + $power`
}


# Iterate through the command line arguments, and store
# each integer in $num.
for num in $@; do
    if [ $num -ge 1 -a $num -le 65536 ]; then     
        # $num squared stored in power variable.
        power=`expr $num \* $num`
        # Output computation result.
        echo "$num squared equals = $power"
        # Call sum() function to evaluate the sum of
        # squared integers.
        sum
    # Else, if argument is over 65536, print user notification that 
    # the maximum number has been reached.
    elif [ $num -ge 65536 ]; then
        echo "65536 is the maximum number for this script"
        exit 1
    # Otherwise; when the arguments are not in range of 0-65536,
    # prompt user why shell executes prematurely.
    else
        # User notification.
        echo "$num is an invalid argument. Only natural numbers from 0 to 65536 are valid."
        # Exit shell script.
        exit 1
    fi
done

# Print out the sum of the sqaured number list.
echo "Total sum of the squared integers: $total"
# Exit shell script.
exit 0

Everything runs fine except when I type in a sting as argument I get the following error:

[: 63: Illegal number: string

I want that whatever input is provided a custom error message is printed instead of that error code above. Any hints on that are greatly appreciated.

-Daniel

Redirect the undesired message to /dev/null

if [ $num -ge 1 -a $num -le 65536 ] 2> /dev/null ; then  

Thanks,

but that doesn't work. I still get the same line.

OK, need to trap the error on this line to:

 elif [ $num -ge 65536 ] 2> /dev/null; then
1 Like

It works, you have been a great help. Thank you :slight_smile:

Hi,
Strings are not evaluated with -ge thats the issue here.
you can use pattern matching or regex to check the arguments to avoid runtime exception if your shell supports.
Else

c=`echo "$num"|awk '/[^0-9.]/{print "0";}'`
if [ $c -eq 0 ]
then 
 echo "Args should have only digits"
 exit
fi

Cheers,
Ranga:-)