February 2004
Beginner
200 pages
5h 40m
English
The if statement chooses between alternatives, each of which may have a complex test. The simplest form is the if-then statement:
ifcommandIf exit status of command is 0 thenbodyfi
For example:
if [ `whoami` = "root" ] then echo "You are the superuser" fi
Next is the if-then-else statement:
ifcommandthenbody1elsebody2fi
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:
ifcommand1thenbody1elifcommand2thenbody2elif ... ... elsebodyNfi
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"
;;
esacThe general form is:
casestringinexpr1)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 ...