Conditional Structures
Intro
If this happens (
if
) - Do this If this either happens (elif
) - Do this If none of the previous (else
) - Do thisfi
Example:
#!/bin/bash
number=$RANDOM
echo -n "Type a number" # -n doesn't jump, stays in the same line
read player
if test $number -eq $player
then
echo "Congrats!"
elif test $number -gt $player
then
echo "Your number is lower"
else
echo "Your number is greater"
fi
echo "the number of player is $player"
echo "the random number is $number"
Controlling inputs
#!/bin/bash
# we want two parameters
if test $# -ne 2
then
echo "Usage: $0 <number1> <number2>"
exit
fi
result=$(($1*$2))
echo "the result is $1 * $2 = $result"
Menus -> Case
Alternative to
switch
from other languagesUseful for menus in scripts
echo "introduce option" read option case $option in 1) echo "option 1" ;; 2) echo "option 2" *) echo "introduce a valid option" ;; esac
#!/bin/bash
echo -n "Introduce an option [1-2]"
read option
case $option in
1)
echo "Option 1 chosen"
;;
2)
echo "Option 2 chosen"
;;
*)
echo "Wrong number selected, choose [1-2]"
;;
esac
Last updated