KornShell - test with a variable that cannot be 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 does not have an extension, and this leads to the FILE_EXT variable FILE_EXT empty, which causes the following error: ./script[37]: test: 0403-004 Specify a parameter with this command.

How do I call this function so that I don't get this error?

+4
source share
6 answers

You must leave the square brackets when you check the function exit code, otherwise you will always get "true". In addition, you must specify your variable. You can add an additional test for an empty extension, as shown below:

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

Edit: Added test for processing file names that end in ..

+5
source

I would do this:

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

If all you want to do is determine that the file has a numerical extension

${FILE_EXT:="no"} will expand to FILE_EXT or 'no' if FILE_EXT is null or empty.

+1
source

you must use ${FILE##*.} with a double "#". Also, what do you mean, the $ FILE_EXT variable will be empty? if your file does not have an extension, then when you make ${FILE#*.} , you will get just the file name in FILE_EXT . how is it empty?

+1
source

Assuming ksh93, you can use your own arithmetic. But we have to be careful: Just ((n)) will fail if n == 0, so we check for ((n ||! N)), which should always be true for any eigenvalue.

To prevent ksh from exiting, we run the expression in the subshell (), adding spaces to prevent conflicts with the arithmetic expression ((...)).

Finally, we close stderr with '2> & -' to prevent any error messages from non-numeric arguments, although you might want to keep them.

 function isNumeric { ( typeset n=${1:?} ((n||!n)) ) 2>& - } 
+1
source

[ -z "$1" ] will check for empty $1 , just like [ "" = "$1" ] .

Or you can simply add “0” to $1 (ie, "0$1" ) to make it non-empty before checking if it is numeric (if you want empty extensions to be treated as numeric).

0
source

I had some problems running your script (maybe because I used pdksh). So I adjusted it a bit. Try the following:

 #!/usr/bin/ksh FILE=$1 FAILURE=1 SUCCESS=0 isNumeric () { if [ -n "$1" ] then case $1 in *[!0-9]* | "") echo "$1 not a number" return $FAILURE ;; * ) echo "$1 is a number" return $SUCCESS ;; esac else echo "parameter is empty" return $FAILURE fi } #... FILE_EXT=${FILE#*.} echo $FILE_EXT isNumeric "${FILE_EXT}" if [ "$?" = "0" ] then echo "Numbered file." fi 
0
source

All Articles