How to use case statements in Bash
A case statement is a conditional statement in Bash that allows you to compare a variable with multiple values. This type of comparison is accomplished with if statements, but case statements are a better alternative to writing them simply and concisely.
The way case statements are used in Bash is similar to how switch statements are used in languages like Java and JavaScript.
Syntax
Let's look into the widget below to understand the case statement syntax in Bash better:
case variable inpattern1)action1;;pattern2)action2;;...*)default_command;;esac
Here’s what each keyword in the syntax above means:
casesignifies the beginning of the case statement.variable incompares the value in the variable according to each pattern; if it evaluates to true, then the action belonging to that pattern is executed.pattern1andpattern2represent the values to which the variable is compared.action1andaction2commands are executed once a pattern matching evaluates to true.;;represent the block end; it represents the end of the code block and stops from continuous execution once an action is executed.*)is a default case that is executed when patterns don't match.esacsignifies the end of the case statement.
Example
After getting a proper understanding of the syntax, its time for us to get hands-on experience with the following widget:
#!/bin/bashread actioncase $action in"code")echo "Write some code";;"sleep")echo "Take some rest";;"exercise")echo "Time for gym";;*)echo "Do nothing";;esac
Enter the input below
The example above illustrates how to use case statements in Bash.