Home > Software engineering >  Shell Program if statements aren't working
Shell Program if statements aren't working

Time:09-15

#!/bin/bash
clear
echo "Wishing according to Time of the PC"
h=$(date  ' %H')  #This line works, I've Checked.
if test $h -gt 6 -a $h -lt 12
then
    echo "Good Morning"
elif test $h -gt 12 -a $h -lt 16
then
    echo "Good Afternoon"
elif test $h -gt 16 -a $h -lt 20
then
    echo "Good Evening"
else
    echo "Good Night"
fi

Output should be coming according to My PC's time which is 4:00 PM but the above code isn't executing that if and elif conditions (I mean, if and elif are always returning false) and is directly jumping to else part. I am using Linux 7.9. I tried using nested if as well but it returns false always as well.

CodePudding user response:

  • you're not capturing when $h is 16
  • only when it's less or more
  • see -ge (greater than or equal to) in the below

allow me to make this more idiomatic (use of test is not current practice, use [[ ... ]]):

h=$(date ' %H')
h=${h#0}        # remove leading zero
if   [[ $h -gt 6  && $h -lt 12 ]]
then
    echo "Good Morning"
elif [[ $h -ge 12 && $h -lt 16 ]]
then
    echo "Good Afternoon"
elif [[ $h -ge 16 && $h -lt 20 ]]
then
    echo "Good Evening"
else
    echo "Good Night"
fi

note that I remove any leading zero, this is because a leading zero can make a number (e.g. 09) interpreted as an octal, which is not what you want!

  • Related