O'Reilly logo

Learning the bash Shell, Second Edition by Bill Rosenblatt, Cameron Newham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

case expression
             in 
            pattern1
             ) 
            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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required