I'm trying to get the date to work properly. The time is 5 pm (1700 hours) now i.e. evening but it always says morning. Here's my code

currenthour="$(date "+ %-H")"
echo $currenthour

if [ $currenthour -gt '12' ] && [ $currenthour -lt '16' ]; then
  currenttimeofday="Afternoon"
elif [ $currenthour -gt '16' ] && [ $currenthour -lt '1' ]; then
  currenttimeofday="Evening"
else
  currenttimeofday="Morning"
fi

echo $currenttimeofday

It's a good idea to post your solution so that others may be helped.

Here is your script with the minimum changes needed to get it to work:

currenthour=$(date "+%-H")
echo "$currenthour"
if [ "$currenthour" -ge 12 ] && [ "$currenthour" -le 16 ]; then
  currenttimeofday="Afternoon"
elif [ "$currenthour" -gt 16 ] && [ "$currenthour" -le 23 ]; then
  currenttimeofday="Evening"
else
  currenttimeofday="Morning"
fi
echo "$currenttimeofday"

A more idiomatic bash version is:

printf -v currenthour '%(%-H)T\n' -1
printf '%d\n' "$currenthour"
if (( currenthour >= 12 )) && (( currenthour <= 16 )); then
  currenttimeofday="Afternoon"
elif (( currenthour > 16 )) && (( currenthour <= 23 )); then
  currenttimeofday="Evening"
else
  currenttimeofday="Morning"
fi
printf '%s\n' "$currenttimeofday"

Edited 2 Years Ago by cfajohnson

This question has already been answered. Start a new discussion instead.