Case Statements in Shell Script:
You can use multiple if...elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Shell supports case...esac statement which handles exactly this situation, and it does so more efficiently than repeated if...elif statements.
Syntax
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Example of the Case :
#!/bin/bash
echo "Which color do you like best?"
echo "1 - Blue"
echo "2 - Red"
echo "3 - Yellow"
echo "4 - Green"
echo "5 - Orange"
read color;
case $color in
1) echo "Blue is a primary color.";;
2) echo "Red is a primary color.";;
3) echo "Yellow is a primary color.";;
4) echo "Green is a secondary color.";;
5) echo "Orange is a secondary color.";;
*) echo "This color is not available. Please choose a different one.";;
esac
Note:
"*" is used if the option is not available in the case.
Functions in Shell Script:
functions enable you to break down the overall functionality of a script into smaller, logical subsections, which can then be called upon to perform their tasks when needed.
Using functions to perform repetitive tasks is an excellent way to create code reuse. This is an important part of modern object-oriented programming principles.
Syntax:
function_name () {
list of commands
}
Example of the Function:
#!/bin/bash
hello_world(){
echo "Hello World"
return
}
hello_world