Case Statement
Learn how the case statement works.
We'll cover the following
A program that follows a conditional algorithm chooses its actions depending on the values of variables. If some variable has one value, the program does one thing. Otherwise, it does something else. The conditional statements of programming languages provide such behaviors.
We considered the if
statement. There is another conditional statement in Bash called case
. It’s more convenient than if
, in some cases.
Document archiving script example
An example will help us to compare if
and case
statements. Let’s suppose that we write a script for archiving documents. The script has three operating modes:
- Archiving without compression.
- Archiving with compression.
- Unarchiving.
We can choose the mode by passing a command-line option to the script. The following table shows the possible options:
Option | Operating mode |
---|---|
-a |
Archiving without compression |
-c |
Archiving with compression |
-x |
Unarchiving |
We should always follow the POSIX convention and its GNU extension when choosing options and parameters format for our scripts. Then, we can learn them faster.
We can check the script option using the if
statement. The following code shows what this solution looks like:
Get hands-on with 1400+ tech skills courses.