Introduction
Hey Ninjas, you must have heard about the if/else or elif statements as a programmer. The if/else statement permits you to create a chain of if statements which is not always the best way, mainly when the values of every branch depend on the same variable. Shell has a Case statement that handles exactly the same problem.
In this blog, we will discuss the Case Statement in Shell.
The Case Statement
Case statements test input values until they match a pattern, executing the command linked with that input value. This makes it an excellent choice for menus where users can select an item to perform a matching action.
The syntax of the Case statement is given below.
case $variableName in
pattern-1)
Statement(s);;
pattern-2)
Statement(s);;
pattern-3)
Statement(s);;
pattern-N)
Statement(s);;
*)
Statement(s);;
esac
Explanation
First, let's understand the meaning of syntax properly.
🧊 The case statement starts with the keyword "Case." After this, we have to give the variable name followed by the "in" keyword.
🧊 We can use more than one pattern case separated by the | operator.
🧊 The ')' operator is used to ending the cases list.
🧊 There must be two semicolons (;;) after every pattern case body.
🧊 We can use special characters in pattern cases.
🧊 The return status is zero if there is no pattern match. Otherwise, it will return the matched pattern as a result.
🧊 The asterisk (*) symbol shows the default case, usually in the final pattern.
🧊 The esac keyword is used at the end of the syntax, which is used to end the program.
Example 1
After understanding the syntax properly, it's time to check the example for better clearance of the concept.
#!/bin/bash
echo "Which one is your favourite fruit?"
echo "1 - Apple"
echo "2 - Mango"
echo "3 - Banana"
echo "4 - Papaya"
echo "5 - Orange"
read fruit;
case $fruit in
1) echo "Apple is my favourite fruit.";;
2) echo "Mango is my favourite fruit.";;
3) echo "Banana is my favourite fruit.";;
4) echo "Papaya is my favourite fruit.";;
5) echo "Orange is my favourite fruit.";;
*) echo "This fruit is not available. Please select a different one.";;
esac
Output
Example 2
This time we will check a different example. Let's see an example with multiple patterns.
#!/bin/bash
echo "Enter planet name: "
read PLANET
case $PLANET in
Mercury | Venus | Earth | Mars | Jupiter | Saturn | Uranus | Neptune)
echo "$PLANET is a planet from the Solar System.";;
Pluto)
echo "$PLANET is a dwarf-planet";;
"Planet Nine") echo "$PLANET not discovered yet";;
*)
echo "$PLANET is not from the Solar System.";;
esac
Output:
Example 3
We will now see the for loop in shell scripting. Let's start with our code.
#!/bin/bash
for ((i=1; i<5; i++))
do
echo $i
done
Output: