I need to greet a user (using “Good morning”, “Good afternoon”, or “Good evening”) depending on the time of day.
I have already gained the users details ($userTitle $userName) however I am not sure how to greet someone differently depending on the time... any ideas?
The expression 2>&1 copies file descriptor 1 to location 2 , so any output written to 2 ("standard error") in the execution environment goes to the same file originally described by 1 ("standard output").
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.
h=`date +%H`
if [ $h -lt 12 ]; then
echo Good morning
elif [ $h -lt 18 ]; then
echo Good afternoon
else
echo Good evening
fi
You could get the time like this:
TIME=$(date "+%H")
Then act on that value i.e
if [ $TIME -lt 12 ]; then
echo "Good morning"
elif [ $TIME -lt 18 ]]; then
echo "Good afternoon"
else
echo "Good evening"
fi
Try doing this :
TIME=$(date "+%k")
if ((TIME < 12 )); then
echo "Good morning"
elif ((TIME < 18 )); then
echo "Good afternoon"
else
echo "Good evening"
fi
-ge
and such. This is just like arithmetic((...))
is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for let
, if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression
hour=`date +%H`
if [ $hour -le 12 ]; then
echo 'good morning'
elif [ $hour -ge 18 ]; then
echo 'good evening'
else
echo 'good afternoon'
fi
All other answers is correct except one detail. Command date +%H
return number hours in
format XX ( for example if time is 09:00:00, then it return "09" ). In bash numbers started with zero is octal numbers. So this nuance can cause errors.
For example:
if [ 09 > 10 ]
then
echo "it's something strange here"
fi
will print "it's something strange here".
Probably you chose time intervals, who are not cause such behavior. But for insurance you can write:
hours=date +"%H" | sed -e 's/^0//g'
Be carefull.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With