Control flow statements are the backbone of making decisions in programming. In scripting, these statements let your scripts decide what to do or how to proceed based on conditions, loops, or user inputs.
Bash and other shell interpreters provides control flow statements like
Most likely you will get to use if-else and for loops more than the others. Therefore, at this level we will focus only on those two control flows.
In simple terms, control flow directs the order in which commands or instructions are executed in a script. It’s like a roadmap that decides which path to take based on certain conditions or how many times to visit a place.
Let’s examine an if-else statement in Bash to understand how it makes decisions based on user input.
The Task:
Our script asks for a number and then tells us if that number is positive, negative, or zero.
The entire script is:
#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
But lets start gradually and understand the entire code from start to finish.
read -p "Enter a number: " num
The Script Breakdown:
Execute the script.
Notice that when you execute the script, it just asks you to Enter a number:. Even when you type a number and hit enter, it takes the number, but you can’t visibly see what it does with the number. That is because the read command in the script has its own way of taking inputs from the user, and storing the value into a variable passed to the read command.
The read command is used to capture user input and store it in a variable. When you use read followed by a variable name (in the case of our script, num), Bash waits for the user to enter something into the command line (stdin). Once the user presses enter, read assigns the input to the variable. Now, lets make more sense of the script. Update the code to the below and execute;
#!/bin/bash
read -p "Enter a number: " num
echo "You have entered the number $num"
Notice how we have now used echo to return back to the screen (stdout) the value stored in the $num variable.
Since we now have something stored in the $num variable, we can use control flow to determine what the script executes next.
if statement
The if statement in Bash scripts allows you to execute commands based on conditions. The basic syntax is:
if [ condition ]; then
commands
fi
Now lets bring it into our code.
if [ $num -gt 0 ]; then
echo "The number is positive."
fi
The part above tests if the value in $num is greater than 0, then most likely you have entered a positive number. Now update your code to the below.
#!/bin/bash
read -p "Enter a number: " num
echo "You have entered the number $num"
if [ $num -gt 0 ]; then
echo "The number is positive."
fi
Notice the keyword -gt in the condition. These are called operators that are used within the condition block to perform numeric comparisons between values.
Run the code and experience the output.
Tip: Always read your shell script line by line to get a sense of what it is doing.
elif statement
After understanding the if statement, we move on to the elif part of control flow in Bash scripts. elif stands for “else if,” allowing you to test additional conditions if the previous if conditions were not met. It helps you add more layers of decision-making to your script. The basic syntax for using elif is as follows:
if [ condition1 ]; then
commands1
elif [ condition2 ]; then
commands2
fi
Now, let’s apply elif to our script to handle a scenario where the entered number might be negative:
#!/bin/bash
read -p "Enter a number: " num
echo "You have entered the number $num"
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
fi
In this updated version of the script:
Notice the -lt “less than” operator in the elif section.
Moving forward in our journey through Bash scripting, we encounter loops. Loops are fundamental constructs that allow us to repeat a set of commands multiple times.
Loops empower us to automate and repeat tasks without writing the same code over and over again. Imagine having to perform a task, like sending a greeting message to each of your friends by name. Without loops, you’d have to write a separate command for each friend, which is not only tedious but also inefficient. Loops streamline this process by allowing you to write a single set of instructions that can be executed as many times as needed, making your script both cleaner and more powerful.
Some real world scenarios where loops are inevitable are;
In Bash scripting, there are three primary types of loops that are commonly used to repeat a set of commands multiple times based on certain conditions.
Lets go through each with examples
The for loop is used to iterate over a list of values or a range of numbers. It is particularly useful when you know in advance how many times you need to execute the loop body.
The for loop has two main forms:
1. List Form: Iterates over a list of items:
Here is a basic syntax;
for item in item1 item2 item3; do
echo $item
done
Lets examine a real example:
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Hello, World! This is message $i"
done
In this example:
echo "Hello, World! This is message $i" prints a greeting along with the current value of i. Once i has taken each value in the list, the loop ends.The same code can also be re-written using a range syntax
for i in {1..5}
do
echo "Counting... $i"
done
Task for you:
2. C-style Form: This style allows you to specify an initializer, condition, and increment/decrement expression. It is based on the same syntax used in doing a for loop in C Programming. Like this;
for (( i=0; i<5; i++ )); do
echo "Number $i"
done
Lets break down the syntax;
- "for (( ... ));": This is the syntax that starts a C-style for loop in Bash. It's distinguished from the list form by the double parentheses "( ... )", which enclose the three parts of the loop: "initialization, condition, and increment/decrement".
- "i=0": This is the initialization part. Before the loop starts, "i" is set to "0". This typically sets up a counter variable to start from a certain value. In this case, i starts from 0.
- "i<5": This is the condition for the loop to continue running. After each iteration of the loop, Bash checks this condition. If it's true, the loop continues; if it's false, the loop ends. Here, the loop will continue as long as **i** is less than "5".
- "i++": This is the increment expression. It's executed at the end of each loop iteration. i++ is shorthand for incrementing i by 1 (i = i + 1). This step ensures that the loop will eventually end by changing the value of i so that the condition i<5 will not always be true.
- "do ... done": Encloses the commands to be executed in each iteration of the loop. Here, the command inside the loop is echo "Number $i", which prints the current value of "i" to the console.
How It Works
- Initialization: Before the first iteration, "i" is set to "0".
- Condition Check: Before each iteration, including the first, Bash checks if i is less than 5.
- If the condition is true, Bash executes the commands inside the loop.
- If the condition is false, Bash exits the loop.
- Execute Commands: The command(s) inside the "do ... done" block are executed. In this case, it prints the current value of "i".
- "Increment:" After executing the commands, "i" is incremented by "1" using the syntax "(i++)".
- **Repeat:** Steps 2 through 4 are repeated until the condition in step 2 is false.
**Lets take a Walkthrough to further expand on your understanding**
- "First Iteration:" i=0, condition 0<5 is true, prints "Number 0", increments i to 1.
- "Second Iteration:" i=1, condition 1<5 is true, prints "Number 1", increments i to 2.
- "Continues iteration" ...
- "Fifth Iteration:" i=4, condition 4<5 is true, prints "Number 4", increments i to 5.
- "Sixth Check:" i=5, condition 5<5 is false, loop ends.
This C-style for loop is powerful for numerical iterations, especially when you need precise control over the start, end, and step size of the loop.
Adding Comments in Bash Scripts
Comments are essential in programming, serving as notes to the programmer and anyone else who might read the code.
They explain what the script or parts of the script do, making the code easier to understand and maintain. This section will guide you on how to add comments in Bash scripts.
Comments are lines in your code that are ignored by the interpreter. In Bash scripts, comments help document the purpose and logic of your code, making it easier for others (and yourself) to follow and understand the script’s functionality.
Single-line comments in Bash start with the # symbol. Anything following this symbol on the same line is treated as a comment and is not executed.
# This is a single-line comment in Bash
echo "Hello, you are learning Bash Scripting on CloudNukes.com!" # This is also a comment, following a command
# This is another way to create
# a multi-line comment. Each line
# is prefixed with a # symbol.
echo "Here is an actual code that gets executed"
This approach is straightforward and is commonly used for adding brief descriptions or notes spanning multiple lines.
At this stage, you’ve established a solid foundation in Bash/shell scripting. (It’s worth noting that Bash and Shell are similar in functionality, which is why their names are often used interchangeably, despite being distinct interpreters.)
Moving forward, you will embark on a capstone project that provides an opportunity for hands-on practice, allowing you to apply your scripting skills in a practical setting and truly immerse yourself in the coding experience.