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.”
-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
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.