Why is the -z to check if the variable is an string is not working on below script

Script is working but is not validating if is string or not, instead it goes to the second if and if i type an string it will tell me (“Invalid month number given. Please enter a valid number - 1 to 12.”) instead of (“No month number given. Please enter a month number as a command line argument.”)

month_number=$1

if [ -z $month_number ]

then

echo “No month number given. Please enter a month number as a command line argument.”

echo “eg: ./print-month-number 5”

exit

fi

if [[ $month_number -lt 1 ]] || [[ $month_number -gt 12 ]]

then

echo “Invalid month number given. Please enter a valid number - 1 to 12.”

exit

fi

if [ $month_number -eq 1 ]

then

echo “January”

elif [ $month_number -eq 2 ]

then

echo “February”

elif [ $month_number -eq 3 ]

then

echo “March”

elif [ $month_number -eq 4 ]

then

echo “April”

elif [ $month_number -eq 5 ]

then

echo “May”

elif [ $month_number -eq 6 ]

then

echo “June”

elif [ $month_number -eq 7 ]

then

echo “July”

elif [ $month_number -eq 8 ]

then

echo “August”

elif [ $month_number -eq 9 ]

then

echo “September”

elif [ $month_number -eq 10 ]

then

echo “October”

elif [ $month_number -eq 11 ]

then

echo “November”

elif [ $month_number -eq 12 ]

then

echo "December"l

fi

Hi,

-z does not test whether the value is a string. It tests whether the value is zero length.

./print-month-number

With nothing after print-month-number then $1 is a zero-length string, and hence so is $month_number by assignment from $1 and thus -z is true and it will print “No month number given. Please enter a month number as a command line argument.” and exit

If you enter a string, e.g.

./print-month-number aaa

then the second if wil be true and you will get “Invalid month number given. Please enter a valid number - 1 to 12.”. The second if checks for the input being a number between 1 and 12

1 Like

From Bash Reference Manual

-z string

True if the length of string is zero.
1 Like

thanks for you time and the response.

Thanks for the info, i was looking for a condition that capture only integer and if string then give you the message that is not an string, but thanks i see -z is not what i thought.

Bash variables are effectively all strings, but if the string is actually an integer number, you can perform numerical operations on it, like -lt, -gt, -eq and shell arithmetic e.g.

x=1
y=2
z=$(($x + $y))
echo $z

3

@Ernesto-Diaz ,

This might help, linux - How do I test if a variable is a number in Bash? - Stack Overflow