Get startedGet started for free

CASE statements

1. CASE statements

Let's learn about CASE statements and how they can help us with tricky IF statement scenarios.

2. The need for CASE statements

CASE statements help create clearer and more efficient code in cases of complex or multiple (perhaps nested) IF statements. Consider the following example of conditionals and actions for a data processing pipeline. If a file contains the word 'sydney' then move it into the 'sydney' directory. If it contains 'melbourne' or 'brisbane' then delete it. Or if it contains the word 'canberra' then change the filename to pre-pend the word IMPORTANT in front of the original filename.

3. A complex IF statement

You already know how to construct multiple IF statements like as follows. We assume you feed in the filename as the first ARGV argument. Then grep checks inside for the words noted previously. Doesn't this seem complex and repetitious?

4. Build a CASE statement

Let's break down the basic CASE statement structure format on the right. Start by identifying which variable or string to match against. This is done by stating case SOMETHING in. The SOMETHING can be a string or a variable. We'll call it STRINGVAR here for convenience. You could even call a shell-within-a-shell and match against the result of this! Then add as many patterns and commands as you like. The STRINGVAR will be checked against each PATTERN and if it matches then the associated code will be run. You can use regex here for the pattern matching if you like. Such as air-star for 'beginning with air'. Remember, each pattern and command need to be separated by a close-parenthesis. Also finish each pattern-command combination with double semi-colons.

5. Build a CASE statement

The last two parts of the CASE statement are as follows. The default match. It is common, though not required, to have a default condition by matching on just a star symbol. If all other pattern matching fails, the code for the default match will run. esac. Finally, finish with the word 'esac'. Which is CASE backwards!

6. From IF to CASE

Let's see the old IF statement previously created here. We can now turn it into a CASE statement using what we learned. We assume the first ARGV element is a filename which we concatenate into the variable to match against. Remember we said we could use a shell-within-a-shell right here? We can use stars on either side of the words as we are regex matching, so the text can have anything before or after our desired word. Notice also the use of OR in the second match for Melbourne OR Brisbane. Finally, we add a default condition printing out that it wasn't recognized.

7. Let's practice!

Let's practice creating some CASE statements in Bash scripts!