If than examples

From Initq
Jump to: navigation, search
#!/bin/sh
set +
echo "Is it morning? Please answer yes or no"
read timeofday
 
if [ $timeofday = yes ]
then
 echo "Good morning"
elif [ $timeofday = no ]
then
 echo "Good evening"
else
 echo "Input in invalid"
 exit 1;
fi
 
exit 0
$ ./morning.sh 
Is it morning? Please answer yes or no
yes
Good morning
$ ./morning.sh 
Is it morning? Please answer yes or no
no
Good evening
$ ./morning.sh 
Is it morning? Please answer yes or no
oh no
[: 15: oh: unexpected operator
[: 15: oh: unexpected operator
Input in invalid

If you do not enter yes or no and just hit enter then you will get

$ ./morning.sh 
Is it morning? Please answer yes or no
 
[: 15: =: unexpected operator
[: 15: =: unexpected operator
Input in invalid

To avoid this you have to put $timeofday in quotes. "$timeofday"

Personal tools