case compares one word with a list of patterns, and runs the lines of the first that matches. For one word with many choices, it reads better than a row of elifs.
#!/bin/bash
# Usage: lights.sh on|off
case "$1" in
on|up)
echo "lights on" ;;
off|down)
echo "lights off" ;;
*)
echo "usage: lights.sh on|off" >&2
exit 2 ;;
esaclearner@reef:~$ ./lights.sh up
lights on
learner@reef:~$ ./lights.sh dim
usage: lights.sh on|off ← no pattern above matched, so *) ran| Part | Means |
|---|---|
on|up) | A pattern. | means "or" |
;; | The end of this choice |
*) | Anything else. It goes last |
esac | The end of the case |
The shop's sign reads ~/shop/state. Write ~/shop.sh to change it:
| You type | shop.sh |
|---|---|
open | Writes open to ~/shop/state |
close | Writes closed to ~/shop/state |
status | Prints what ~/shop/state holds |
| anything else | Writes usage: shop.sh open|close|status as an error, exit code 2 |
-
Write it with
nano ~/shop.sh: onecase "$1" in, with a choice for each row. Put the usage line in double quotes, or each|in it is a pipe. -
Make it runnable and try it:
textlearner@reef:~$ chmod u+x ~/shop.sh learner@reef:~$ ./shop.sh open learner@reef:~$ ./shop.sh status open -
Try
closeand a word it doesn't know.
Objectives
openandcloseset the sign.statusprints it.- Anything else is refused.