Hello, I wrote the case on code but it mistakes. I am not sure.
If/elif code:
#!/bin/ksh
you=$LOGNAME
hour=`date | awk '{print substr($4, 1, 2)}'`
print "The time is: $(date)"
if (( hour > 0 && $hour < 12 ))
then
print "Good morning, $you!"
elif (( hour == 12 ))
then
print "Lunch time!"
elif (( hour > 12 && $hour < 16 ))
then
print "Good afternoon, $you!"
else
print "Good night, $you!"
fi
Change Case code:
#!/bin/ksh
you=$LOGNAME
hour=`date | awk '{print substr($4, 1, 2)}'`
print "The time is: $(date)"
case $hour in
(hour > 0 && $hour < 12 ) echo "Good morning, $you!";;
(hour == 12 ) echo "Lunch time!";;
(hour > 12 && $hour < 16 ) echo "Good afternoon, $you!;;
echo "Good night, $you!";;
esac
Did I mistake this the case?
Thanks,
case does not work that way. It matches strings and does not contain logical statements. if / else is what you needed.
You can do it with case by pure string matching but it'd be awkward;
case "$hour" in
[0-9]|1[01]) echo "good morning" ;;
12) echo "lunch time"
1[3-6]) echo "good afternoon" ;;
*) echo "good night" ;;
esac
1 Like
Yes, a case
statement can only use pattern matching, not numerical comparisons...
1 Like
Aia
4
An unrelated comment if you do not mind:
hour=`date | awk '{print substr($4, 1, 2)}'`
Pipes are great but sometimes unnecessary. Many times the first program have the figure or ability already built-in.
hour=`date "+%H"`
1 Like
I got some errors.
#!/bin/ksh
you=$LOGNAME
hour=`"+%H"`
print "The time is: $(date)"
case "$hour" in
[0-9]|1[0-1]) echo "good morning" ;;
12) echo "lunch time"
1[3-7]) echo "good afternoon" ;;
*) echo "good night" ;;
esac
It said, "line 5: syntax error at line 10: `)' unexpected"
The double semicolon is missing in
12) echo "lunch time" ;;
And, a bit earlier, date
is missing.
I forgot the ;; after "lunch time".
Also, your "+%H" command does not work. That's not a command, that's an argument. You should do this:
hour=$(date +%H)
Oop! I didn't see it! it worked. Thanks guys! This is closed.