Case Statement
Explore the Bash case statement to control script execution based on variable values. Understand its syntax, compare it with if statements, and apply it to practical scripting scenarios for automation.
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: