Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KornShell - Test with variable that may be not set

I have the following code in KornShell (ksh):

FAILURE=1
SUCCESS=0

isNumeric(){

    if [ -n "$1" ]; then
        case $1 in
            *[!0-9]* | "")  return $FAILURE;
                       * )  return $SUCCESS;
        esac;
    else
        return $FAILURE;
    fi;
}

#...
FILE_EXT=${FILE#*.}

if [ isNumeric ${FILE_EXT} ]; then
    echo "Numbered file."
fi
#...

In some cases the file name not have an extension, and this causes the FILE_EXT variable to be empty, which causes the following error: ./script[37]: test: 0403-004 Specify a parameter with this command.

How should I be calling this function so that I do not get this error?

like image 464
C. Ross Avatar asked Feb 28 '23 22:02

C. Ross


1 Answers

You should leave off the square brackets when you are testing the exit code of a function, otherwise, you'll always get "true". Also, you should quote your variable. You could put an additional test for an empty extension as shown:

FILE_EXT=${FILE#*.}

if isNumeric "${FILE_EXT}" &&
    [ "${FILE_EXT}" != "${FILE}" -a "${FILE_EXT}" != "" ]
then
    echo "Numbered file."
fi

Edit: added test to handle filenames that end in "."

like image 195
Dennis Williamson Avatar answered Apr 08 '23 15:04

Dennis Williamson