-2

I am trying to run the following script in bash

#greetings
set `date`
if [ "$4" -lt 12 ]
then 
  echo "Good Morning"
elif [ "$4" -lt 18 ]
  echo "Good Afternoon"
else
  echo "Good evening"
fi
exit

I keep geeting the error ./greetings: line 3: [: 06:19:20: integer expression expected

What should i do?

2 Answers2

1

If you try to echo $4 at the very beginning of the script, you'll get a result of the following format:

%H:%M:%S

For example,

$ date
16:41:22

This result can't be parsed as integer.

One solution would be setting only the hours instead of the whole date, and use $1 (instead of $4):

# greetings
set `date +%H`
if [ "$1" -lt 12 ]
then
  echo "Good Morning"
elif [ "$1" -lt 18 ]
then
  echo "Good Afternoon"
else
  echo "Good evening"
fi
exit

Also, please note that you're missing then keyword after elif.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0
TIME=`date +%H:%M:%S | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'`

if [ "$TIME" -lt 43200 ]; then 
  echo "Good Morning"
elif [ "$TIME" -lt 64800 ]; then
  echo "Good Afternoon"
else
  echo "Good evening"
fi
exit

All times are converted to seconds

Prav
  • 2,785
  • 1
  • 21
  • 30
  • @Maroun You're absolutely right. But his question had `H:m:s` format and I wasn't sure I can do that with `date` approach. – Prav Apr 08 '18 at 14:03