In: Computer Science
Beginner's Linux.....for loops, while loops....if/elif/el...commands...simple but clean....please help with comments so I can understand
I have executed this in Linux Ubuntu.
To execute this script, I saved it as thirsty.sh. Then we make this executable with the command: chmod +x thirsty.sh
To run this, we use : ./thirsty.sh
Since you wanted a basic script, I executed this using only if, elif and else
If, else, elif statement syntax:
if [ expression 1 ] then Statement(s) to be executed if expression 1 is true elif [ expression 2 ] then Statement(s) to be executed if expression 2 is true elif [ expression 3 ] then Statement(s) to be executed if expression 3 is true else Statement(s) to be executed if no expression is true fi
The if...elif...fi statement is the one level advance form of control statement that allows Shell to make correct decision out of several conditions.
#!/bin/sh
n2="No" # storing value of No in n2
n3="no" # storing value of no in n3
n4="Yes" # storing value of Yes in n4
n5="yes" # storing value of yes in n5
water="water" # # storing value of water in water
beer="beer" # storing value of beer in beer
wine="wine" # storing value of wine in wwine
something=" " # if user enter something else, it checks here
echo "Are you thirsty" # echo to print statement
read n1 #reading the user response and storing in n1
if [ "$n1" = "$n2" ] || [ "$n1" = "$n3" ] # if statement to compare two values
then # we use || (pipe) also know as OR which is used to compare two values
echo "You're not thirsty. We'll exit now"
elif [ "$n1" = "$n4" ] || [ "$n1" = "$n5" ] # elif statement to compare two values
then
read -p "What would you like to drink: " d1 #storing in d1
if [ "$d1" = "$water" ] # comparing d1 with water
then
echo "Clear crisp and refreshing" # if true, this is printed
elif [ "$d1" = "$beer" ] # comparing d1 with beer
then
echo "Let me see some id" #if true, this is printed
elif [ "$d1" = "$wine" ] comparing d1 with wine
then
echo "one box or two"
else # if nothing is true, else is executed
echo "Coming right up." # executes when if is not executed
break # breaks the statement and the script closes
fi # closing if statement with fi
fi # closing if statement with fi
Output:
All the given conditions were verified
If you have any doubts, leave a comment below before rating. I'll be happy to assist you further.
Do UPVOTE this as I have put a lot of EFFORT in answering this question. It really helps me.