Bash Scripting: Control Stuctures
Bash Scripting: Control Structures
In Bash scripting, control structures allow you to make decisions based on conditions and perform different actions depending on the result. There are two types of control structures: the if statement and the case statement.
The if statement
The if statement is used to test a condition and perform different actions depending on whether the condition is true or false.
Here is the basic syntax of the if statement:
Let's break down the different parts of this syntax:
-
if: This keyword starts theifstatement. -
[ condition ]: This is the condition that we want to test. Note that there is a space after the opening bracket and before the closing bracket. -
then: This keyword indicates that we are about to execute a command if the condition is true. -
# do something if the condition is true: This is the command that will be executed if the condition is true. -
else: This keyword indicates that we are about to execute a command if the condition is false. -
# do something else if the condition is false: This is the command that will be executed if the condition is false. -
fi: This keyword ends theifstatement.
Here is an example that shows how the if statement can be used:
This script checks if the /etc directory exists and if it is a directory. If it is, then it prints out the message " /etc is a directory". If it is not, then it prints out the message " /etc is not a directory".
The case statement
The case statement is used to test a value against a list of possible patterns and perform different actions depending on which pattern matches.
Here is the basic syntax of the case statement:
Let's break down the different parts of this syntax:
-
case: This keyword starts thecasestatement. -
$variable: This is the value that we want to test against the list of patterns. -
in: This keyword indicates that we are about to list the patterns. -
pattern1): This is the first pattern that we want to test. Note that the pattern ends with a closing parenthesis. -
# do something if $variable matches pattern1: This is the command that will be executed if the value of$variablematchespattern1. -
;;: This keyword ends the command for this pattern and starts the next pattern. -
pattern2): This is the second pattern that we want to test. -
# do something if $variable matches pattern2: This is the command that will be executed if the value of$variablematchespattern2. -
;;: This keyword ends the command for this pattern and starts the next pattern.


