case
The next flow-control construct we will cover is case. While the case statement in Pascal and the similar switch statement in C can be used to test simple values like integers and characters, bash’s case construct lets you test strings against patterns that can contain wildcard characters. Like its conventional-language counterparts, case lets you express a series of if-then-else type statements in a concise way.
The syntax of case is as follows:
caseexpression
inpattern1
)statements ;;
pattern2
)statements ;;
...
esac
Any of the patterns can actually be several patterns separated by pipe characters (|). If expression matches one of the patterns, its corresponding statements are executed. If there are several patterns separated by pipe characters, the expression can match any of them in order for the associated statements to be run. The patterns are checked in order until a match is found; if none is found, nothing happens.
This construct should become clearer with an example. Let’s revisit our solution to Task 4-2 and the additions to it presented earlier in this chapter, our graphics utility. Remember that we wrote some code that processed input files according to their suffixes ( .pcx for PCX format, .jpg for JPEG format, etc.).
We can improve upon this solution in two ways. Firstly, we can use a for loop to allow multiple files to be processed one at a time; secondly, we can use the case construct to streamline the code:
for filename in "$@"; do ppmfile=${filename%.*}.ppm ...
Get Learning the bash Shell, Second Edition 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.