Chapter 3. Just in CASE
Many programming languages provide a âswitchâ or âmatchâ statement, an n-way branch, used as an alternative to a string of if
/then
/else
clauses. There is a similar construct in bash: the case
statement.
It comes with powerful pattern matching and is very useful in scripting.
Make Your Case
The keywords case
and in
delineate the value you want to compare against various patterns.
Hereâs a simple example:
case
"
$var
"
in
yes)
echo
"glad you agreed"
;;
no)
echo
"sorry; good bye"
exit
;;
*)
echo
"invalid answer. try again"
;;
esac
â¦which you can probably figure out.
It checks to see if the value in $var
is âyesâ or ânoâ and executes the corresponding statement(s). It even has a default action.
The end of the case statement is marked by esac
, which is case spelled backward.
This example is pretty readable, but it just scratches the surface. Youâll also note that you used two different block styles, a âone-linerâ for yes and a more typical block (closed by ;;
â¦more on that later) for no. Which you use depends on what you are doing and how the code lines up for readability.
(
in case
The syntax for the case
statement includes an optional â(â to match the â)â in the example. For example, we could have written ("yes")
instead of just "yes")
and similarly for the other items. Weâve rarely seen this used, though. After all, who wants to type an extra character?
The real power of the case
statement, and the most idiomatic appearance, ...
Get bash Idioms now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.