Control Flow in Bash

Control Flow in Bash

In my previous article we looked into how Variables are declared and used in Bash. If you haven't read it yet , I encourage you to do so here. In this article we are going to dive deeper into the world of Bash scripting , specifically the concept of control flow.

Now , if you are coming from a software engineering background or you understand programming languages then control flow is not a foreign concept to you . However if you are new to this then this article will definitely help you to not only understand how its done in Bash but in other programming languages as well.

Control flow is a fundamental concept in programming languages that dictates the order in which statements are executed within a program. It enables you to make decisions, iterate over data, and control the flow of execution based on conditions or other factors. Control flow constructs allow you to create dynamic and flexible programs that can respond to different inputs and conditions.

In Bash, control flow allows you to execute commands conditionally, iterate over data, and control the flow of execution within a script. So how exactly is it done ?

Conditional Statements

Conditional statements in Bash allow you to make decisions based on the evaluation of conditions. The most common conditional statements in Bash are the if, elif (else if), and else statements.

Lets take a look at the if statement:

The if statement allows you to execute a block of code conditionally based on the evaluation of a condition. So if the condition is true , execute some lines of code or a particular command . If the condition is false , then do something else instead. The syntax in Bash is as follows:

if [ condition ]; then
    # Code block to execute if condition is true
else
    # Code block to execute if the above conditions is false
fi
   # End of if statement        

if [ condition ]; then: This line marks the beginning of the if statement. The condition is enclosed within square brackets ([ ]) is what will be evaluated. If the condition evaluates to true the subsequent code block is executed.

else: If the conditions evaluate to false, the code block following the else statement is executed.

fi: This marks the end of the if statement. It is the reverse spelling of if.

So how does this help us make a decision or alter the flow of execution ?

Here's an example, you have an application that manages reservations for a nightclub or a pub or a bar . The condition that needs to be met in this case , is that for a customer to be allowed to make a reservation , they have to be above 21 years of age. If they are , then are allowed to make the reservation if not then they are denied access. We are making this decision based on if the age condition has been met or not. This is a hypothetical of course. A more realistic example of how a bash script would use an if statement , let's say you landed a job as a DevOps Engineer at a local startup and part of your job description , you are required to make backups regularly. But you've read my articles and you know that you can automate this process(You're welcome).

You write a script to automate the backup process for a server. Your script needs to check if there is enough available disk space before initiating the backup. If there is sufficient space, the backup process should proceed. Otherwise, the script should halt and display an error message indicating that there is not enough space for the backup.

Here's how you could implement this using an if statement in Bash I actually wrote the script on my system:

Article content

Don't worry if there are some commands you don't understand like awk ,df -h, i will cover them in another article. Also the # signifies a comment.

We use an if statement to compare the available space on the server with the threshold. If the available space is greater than the threshold, the script displays a message indicating that there is sufficient space and proceeds with the backup process. Otherwise, it displays an error message indicating that there is not enough space, and further action can be taken, such as halting the script or performing error handling.

So the if statement is helping us make that decision based on the condition being met or not in this case if available disk space is sufficient then our backup will proceed if not then no back up will be done. Of course we could make our script better but I'm just using it as an example to drive the point home.

Multi-Conditional Checks

Some times you want to evaluate more than one condition . In Bash scripting, elif is short for "else if" and is used as part of the if statement to evaluate additional conditions if the initial if condition is false. It allows you to create branching logic with multiple conditional checks. The syntax for using elif in Bash is as follows:

if [ condition1 ]; then
    # Code block to execute if condition1 is true
elif [ condition2 ]; then
    # Code to execute if condition1 is false and condition2 is true
elif [ condition3 ]; then
    # Code to execute if both condition1 and condition2 are false and condition3 is true
else
    # Code block to execute if none of the above conditions are true
fi        

You can see we are checking for more than one condition in the above syntax explanation. Here is a simple script that checks if a number is positive , negative or zero, this requires multiple conditions to be either true or false.

Article content

In this example:

  • If the user enters a number greater than 0, the script prints "The number is positive."
  • If the user enters a number less than 0, the script prints "The number is negative."
  • If the user enters 0, the script prints "The number is zero."

The elif statement allows you to check multiple conditions sequentially, providing flexibility in creating decision-making logic in Bash scripts.

Point to note : The read command is used to read input from the user or from a file and store it in a variable. It allows your Bash script to interact with users by prompting them for input and then capturing that input for further processing within the script. -gt is a comparison operator used to evaluate whether one numerical value is greater than another. It stands for "greater than." So $num -gt 0 is checking whether the value stored in the variable num is greater than 0.

Other comparison operators in Bash include:

  • -lt: Less than
  • -ge: Greater than or equal to
  • -le: Less than or equal to
  • -eq: Equal to
  • -ne: Not equal to

These operators are commonly used in conditional statements (if, elif) to perform numerical comparisons and make decisions based on the results.

Now , I know this is a lot of information to take in at once , my advice is take time and practice writing if statements , as well as using the comparison operators.

In the next article we take a look at loops and how they are used to iterate over a set of data or perform repetitive tasks in Bash scripts.


No. The syntax of an if statement in bash is *not* "if [ condition ]; then". This is a fundamental error that causes a great deal of unnecessary anguish. The syntax is "if command; then" or "if command1; command2; ...; commandN; then". There is no "conditional". You are executing a command (or pipeline, or sequence of commands) and evaluating the status of those commands. Remove "condition" from your mind. It is *not* "if boolean-condition", and there is certainly no requirement to use "[". The misconception that "[" is part of the grammar has confused countless people trying to learn bash (or any shell).

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore content categories