Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 56

Bash Scripting: Control Structures

Recommended resources

Hello! Welcome to a new module in your DevOps mastery journey: Scripting and Automation with Bash.

In the previous modules, you've built a solid foundation in Linux and version control with Git. You've learned how to manage your code and collaborate on projects. Now, we shift our focus to one of the most powerful skills in a DevOps engineer's toolkit: automation. Bash scripting is the glue that allows you to automate repetitive tasks, manage systems, and orchestrate complex workflows directly from the command line.

This first lesson gets straight to the core of scripting logic. You'll learn how to make your scripts "think" and repeat actions.

Today's Learning Outcome: By the end of this lesson, you will be able to write Bash scripts with control structures, including if, for, and while loops.

Shell Script Control Structures
This image provides a great visual overview of the three core control structures we will cover today: conditional `if-else` statements, `case` statements for multiple choices, and `for` loops for iteration.

A Quick Refresher: What is a Bash Script?

Remember from our early Linux lessons, a shell script is simply a text file containing a sequence of commands. When you run the script, the shell executes these commands one by one. To make scripts more powerful, we need to add logic.

All our scripts will start with a shebang: #!/bin/bash. This line tells the system to execute the script using the Bash interpreter.

And to run a script, you first need to make it executable:
chmod +x your_script_name.sh

Then, you can run it like this:
./your_script_name.sh

Now, let's add some intelligence to our scripts.


1. Making Decisions with if, elif, and else

The if statement is the most fundamental control structure. It allows your script to execute a block of code only if a certain condition is true.

The basic syntax is:

if [ condition ]; then
  # code to execute if condition is true
fi

Notice the crucial details:

  • There are spaces inside the square brackets [ ].
  • The statement ends with fi (if spelled backward).

You can add an else block to execute code when the condition is false, and elif (else if) to check for multiple conditions.

if [ condition1 ]; then
  # code for condition1
elif [ condition2 ]; then
  # code for condition2
else
  # code if no conditions are met
fi

To learn the syntax and the essential comparison operators you'll use inside the [ ], please read the following sections from the "Bash Scripting Tutorial".

Bash Scripting Tutorial: A Beginner's Guide

This guide from LinuxConfig provides a clear and structured introduction to conditional statements and the operators you'll need to create effective conditions.

Please read the sections titled 'Bash if / else / fi statements' and 'Bash Comparisons'. Pay close attention to the tables showing the different operators for arithmetic (-eq, -gt, etc.) and string comparisons (=, !=, etc.).

A very common task in DevOps is checking for the existence of files or directories before trying to use them. This prevents errors in your scripts. The if statement is perfect for this.

For a practical example, look at how to check if a file exists in the "25 Practical Linux Bash Script Examples" article.

25 Practical Linux Bash Script Examples to Automate Your ...

This article from Elementor's blog gives a concise, real-world example of using an if statement for a common administrative task.

Read example #7, 'Checking if a File Exists'. Note the use of the -f operator to test for a file.

Test your understanding!

Write a simple Bash script that checks if the directory /var/log exists. If it does, it should print "Log directory found." If it doesn't, it should print "Log directory not found." (Hint: The operator to check for a directory is -d).

Show answer
#!/bin/bash

DIRECTORY="/var/log"

if [ -d "$DIRECTORY" ]; then
  echo "Log directory found."
else
  echo "Log directory not found."
fi

This script uses the -d test within an if statement to check for the existence of the /var/log directory and prints a message based on the result.


2. Repeating Actions with Loops

Loops are used to execute a block of code multiple times. This is essential for automating tasks that involve multiple items, like processing a list of servers, files, or users.

The for Loop: Iterating Over a List

A for loop is ideal when you have a known set of items you want to iterate through.

The syntax is:

for variable in item1 item2 item3; do
  # code to execute for each item
  # you can use $variable here
done

for loops are incredibly versatile. You can loop over a static list, a sequence of numbers, or the output of another command.

The while Loop: Looping While a Condition is True

A while loop continues to execute as long as its control condition is true. This is perfect for when you don't know in advance how many times you need to loop.

The syntax is:

while [ condition ]; do
  # code to execute as long as condition is true
done
While Loop Flowchart
This flowchart illustrates the logic of a `while` loop. The condition is tested *before* each iteration. If it's true, the loop body executes, and the cycle repeats. If it's false, the loop terminates.

To see the syntax and examples for both for and while loops, let's return to the "Bash Scripting Tutorial".

Bash Scripting Tutorial: A Beginner's Guide

This section covers the three main loop types in Bash, providing simple examples that clearly demonstrate how each one works.

Read the section titled 'Loops', focusing on the 'Bash for loop' and 'Bash while loop' subsections. The 'until' loop is also good to be aware of—it's just the inverse of a 'while' loop.

Now let's look at some more practical examples of these loops in action.

25 Practical Linux Bash Script Examples to Automate Your ...

These examples demonstrate common DevOps use cases for loops: iterating over a list of servers with a for loop and reading a file line-by-line with a while loop.

Read example #8, 'The for Loop for Iteration', and example #10, 'while Loop for Reading a File Line by Line'. These showcase powerful, real-world patterns.


3. Alternative Control Structures

While if, for, and while are the workhorses of Bash scripting, it's useful to know about two other structures.

  • until loop: This is the opposite of a while loop. It runs until a condition becomes true.
  • case statement: This is a cleaner way to handle multiple choices, acting as a powerful alternative to a long chain of if/elif statements.

You can find excellent examples of both the until loop and case statements in the resources you've already reviewed (LINK and LINK). We won't dive deep into them now, but it's good to know they exist for when you need them.

Test your understanding!

Let's combine what we've learned. Write a script that uses a for loop to iterate through the numbers 1 to 5. Inside the loop, use an if statement to print whether the number is "Odd" or "Even".

(Hint: You can use the arithmetic expression (( number % 2 == 0 )) to check if a number is even.)

Show answer
#!/bin/bash

for i in {1..5}; do
  if (( i % 2 == 0 )); then
    echo "$i is Even"
  else
    echo "$i is Odd"
  fi
done

This script uses a for loop to create the sequence of numbers. Inside the loop, the if statement checks the remainder of the number when divided by 2. The ((...)) syntax is used for arithmetic evaluation in Bash.


Conclusion

You've just learned the fundamental building blocks of logic in Bash scripting. With these tools, you can move beyond simple command sequences and start writing powerful scripts that automate real-world tasks.

Key Takeaways:

  • if, elif, else: Use these to make decisions and execute different code paths based on conditions.
  • Comparison Operators: You must use the correct operators for numbers (-eq, -gt, etc.) and strings (=, !=). File tests (-f, -d) are also essential.
  • for loop: Best for iterating over a known list of items (e.g., files in a directory, a list of servers).
  • while loop: Best for looping an unknown number of times until a specific condition is met (e.g., reading a file line by line, waiting for a process to finish).

In our next lesson, we will make our scripts even more flexible and powerful. You'll learn how to handle command-line arguments and options, allowing you to pass information into your scripts when you run them.