The if
statement chooses
between alternatives, each of which may have a complex test. The
simplest form is the if-then
statement:
ifcommand
If exit status of command is 0 thenbody
fi
For example:
if [ `whoami` = "root" ] then echo "You are the superuser" fi
Next is the if-then-else
statement:
ifcommand
thenbody1
elsebody2
fi
For example:
if [ `whoami` = "root" ] then echo "You are the superuser" else echo "You are an ordinary dude" fi
Finally, we have the form if-then-elif-else
, which may have as many
tests as you like:
ifcommand1
thenbody1
elifcommand2
thenbody2
elif ... ... elsebodyN
fi
For example:
if [ `whoami` = "root" ] then echo "You are the superuser" elif [ "$USER" = "root" ] then echo "You might be the superuser" elif [ "$bribe" -gt 10000 ] then echo "You can pay to be the superuser" else echo "You are still an ordinary dude" fi
The case
statement evaluates
a single value and branches to an appropriate piece of code:
echo "What would you like to do?" read answer case "$answer" in eat) echo "OK, have a hamburger" ;; sleep) echo "Good night then" ;; *) echo "I'm not sure what you want to do" echo "I guess I'll see you tomorrow" ;; esac
The general form is:
casestring
inexpr1
)body1
;;expr2
)body2
;; ...exprN
)bodyN
;; *)bodyelse
;; esac
where string
is any value, usually a
variable value like $myvar
, and
expr1
through
exprN
are patterns (run the command
info bash reserved case
for
details), with the final *
like a
final “else.” Each set of commands must be terminated by ;;
(as shown):
case $letter in X) echo "$letter is an X" ;; [aeiou]) echo "$letter is a vowel" ;; [0-9]) echo "$letter is a digit, silly" ;; *) echo "The letter '$letter' is not supported" ;; esac
3.145.131.238