What Are if, elif, and else Statements in Bash Scripts

Try this guide with our instant dedicated server for as low as 40 Euros

if elif else Statement

By providing your email address or using a single sign-on provider to create an account, you agree to our Terms of Service and that you have reviewed our Privacy Policy.

Thank you for contacting us! We will get in touch with you soon.

Steve Bourne created the Bourne Again Shell (Bash) as an enhanced version of the original shell (sh). Bash scripting is a way to automate tasks in Linux operating systems using the capabilities of the Bash shell. 

A Bash script is a series of commands in a file that can be executed as a program. When you run a Bash script, the shell processes the script line by line, executing each command as if you are entering it manually. As a result, shell scripts are a great way of saving time and reducing the potential for human error.

This comprehensive tutorial will discuss the if, elif, and else statements in Bash scripts. We’ll start with a short overview of these statements and then do a deep dive into how you can use them in your scripts to execute blocks of command conditionally. 

Table of Contents

  1. An Overview of the if, elif, and Else Statements in Bash Scripting
  2. How to Use if, elif, and else Statements in Bash Scripts
    1. Prerequisites
    2. The Bash if Statement
    3. The Bash elif Statement
    4. The Bash else Statement
  3. Conclusion
  4. FAQs

An Overview of the if, elif, and Else Statements in Bash Scripting

The if, elif, and else statements in Bash scripting are used to make decisions in your scripts. Essentially, they allow you to execute a statement or a statement block only when specific conditions are valid. If the conditions are not met, the execution process follows the alternative branch.

Here’s a basic rundown of these statements:

  • if: It starts the conditional statement and is followed by a condition. If that condition is true (it returns a zero exit status), the commands right after the if block are executed.
  • elif: Short for “else if, this statement provides an additional condition to test if the first if condition evaluates to be false. You can have multiple elif blocks to check for various conditions. Note that if and elif statements are evaluated in sequence.
  • else: This is the final part of the conditional statement structure. If none of the if or elif conditions were evaluated to be true (they all return a non-zero exit status), the commands following else get executed. 

Once the execution has run through this structure, it exits the decision-making and continues with the rest of the commands.

When used together, a typical if, elif, and else block looks like: 

if [ condition ]; then

# Commands if 'condition' is true

elif [ condition2 ]; then

# Commands if 'condition2' is true

else

# Commands if both 'condition' and 'condition2' are false

fi

How to Use if, elif, and else Statements in Bash Scripts

Now that you know about the decision-making statements in Bash scripts, let’s go into the details of implementing these statements in action. Here’re the prerequisites.

Prerequisites

Make sure you have the following before working with the Bash decision-making statements:

  • A system running a mainstream Linux distribution
  • A text editor such as Vi, Vim, or nano
  • Access to the terminal (preferably running Bash)

The Bash if Statement

In Bash, an if statement is a conditional construct used to make decisions in a script. You use these statements to place the condition that can evolve to be true or false. Based on this status, the execution selects the next statement(s) for execution. 

The basic syntax of an if statement in Bash is as follows:

if [ condition ]; then

    # Code to be executed if the condition is true

else

    # Code to be executed if the condition is false

fi

Here’s a breakdown of this syntax:

  • if: This keyword precedes the statement to be evaluated at the start of the conditional statement block.
  • [ condition ]: The condition is enclosed in square brackets and is tested to evaluate to either true or false. You can use various operators and expressions to create conditions, such as comparison operators (-eq (equal to), -ne (not equal to), -lt (less than), -gt (greater than), -le (less than or equal to), -ge (greater than or equal to), string comparisons, file tests, and logical operators (&& for AND, || for OR, ! for NOT).
  • then: This indicates the start of the code block to execute if the condition is true.
  • else: This keyword comes into effect when the if condition is evaluated to be false. You can use this keyword to specify a different statement block.
  • fi: It ends the if statement.

Conditions in Bash if

Bash offers numerous built-in tests and comparisons, which are helpful in different scenarios. You may have come across statements like these in Bash scripts:

if [ $foo -ge 3 ]; then

In this statement, the condition is a command. Using square brackets to enclose a comparison is equivalent to using the built-in test command. The block after then will be performed if $foo is Greater than or Equal to 3 (condition is true). 

If you’ve ever wondered why bash typically uses -ge or -eq rather than >= or ==, it’s because this type of condition comes from a command with the parameters -ge and -eq.

During the execution of the if statement, the condition is tested and returns an exit code. If the condition evolves to be true, the exit code is 0. In case of error, the status code can be an integer between 1 to 255. 

You can test this status code by running the following statement in the terminal:

# test 1 -gt 5

test 1 -gt 5

Next, use the echo command to see the exit status: 

# echo $?

The test returns an exit code of 1, meaning the expression has evolved to be false (1 is NOT greater than 5).

Likewise, use the following statement and see that it successfully evaluates in the terminal (10 is more than 5):

# test 10 -gt 5

test 10 -gt 5

To see the successful exit status, run this:

# echo $?

Bash if Statement Example

Run through the following steps to write an example Bash script with an if statement.

Launch the terminal and create a file named if-stmt_test.sh

Enter the following lines in this file:

# vi if-stmt_test.sh

echo -n "Please enter a number: "

read TEST

echo Your number is $TEST

if test $TEST -gt 5

then

echo "It's greater than 5”

fi

echo Bye!

Close and save the file.

cat if-stmt

After that, enable file execution by setting the proper permissions:

# chmod +x if-stmt_test.sh

Finally, execute the script using this command:

# ./if-stmt_test.sh

Depending on the number entered, the script generates a different message. To verify this behavior, run the script a couple times and check for different numbers.

Here’s the execution flow of the script:

  • Lines 1-3 contains instructions on how to enter a number through the console. The number is printed after being read into the TEST variable.
  • The if statement is initiated in line 4, and the status of the command’s exit is checked immediately after ($TEST -gt 5).
  • The commands on lines 5 and 6 will only be executed if the statement on line 4 is evaluated to be true, with the exit status of 0. This indicates that the user entered a value greater than 5.
  • Line 7 contains the end of the if statement.
  • Regardless of the status of the if statement, line 8 is executed independently as it is outside the if statement block.

Here’s another example of an if statement that checks whether file exists at the given path: 

if [ -e /path/to/file ]; then echo “The file exists.” fi

The -e option within the [ ] test command checks if the file exists.

In an if statement, you can test conditions for string comparison, file existence, and arithmetic evaluation. The [[ ]] is a more modern Bash alternative to [ ] that allows for more advanced features, such as regex and pattern matching.

The Bash elif Statement

In bash, elif stands for “for else”. It is a key component of conditional statements in many programming languages, including Python, C++, and Java. 

It is used to incorporate additional if blocks that present alternative conditions for evaluation until one is evaluated to be true or all are evaluated to be false. Simply put, it is used after an if statement to check another condition if the previous condition(s) were false.

You can have multiple elif blocks for checking various conditions. The basic syntax of the statement is:

elif [another_condition]; 

then # commands to execute if another_condition is true

Bash elif Statement Example

The following is an easy to understand example of using the elif statement:

echo -n "Please enter a whole number: "

read VAR

echo Your number is $VAR

if [ $VAR -gt 10 ]

then

        echo "It's greater than 10"

elif [ $VAR -lt 10 ]

then

        echo "It's less than 10"

else

        echo "It's exactly 10"

fi

echo Bye!

sh elif-stmt

The Bash else Statement

The else statement is used after the if and elif blocks and presents and tests a condition when all the preceding conditions are evaluated to be false.

Bash else Statement Example

Here’s an example of else statement in Bash scripting:

age = 10 

if age >= 18: 

print("You are an adult.") 

elif age < 18 and age >= 13: 

print("You are a teenager.") 

else: print("You are a child.")

In this example, the if and elif statement evaluates to be false (age is neither >= 18 nor between 13 and 18). The else block executes, and the program prints You are a child.

Conclusion

The Bash if, elif, and else statement effectively creates conditional logic in Bash scripts. They allow for executing code blocks based on various conditions, providing flexibility and control by understanding the syntax and usage of if elif else statements. Bash scripters can effectively manage different scenarios and enhance the functionality of their scripts using them. 

RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is the basic syntax of a bash if-else statement?

The basic syntax of a Bash if-else statement is as follows:

if [ condition ]; then

    # Code to be executed if the condition is true

else

    # Code to be executed if the condition is false

fi

Q. How do I use the if-elif-else statement in a bash script to handle multiple conditions?

The if-elif-else statement in Bash allows you to handle multiple conditions sequentially, as in the example below.

if [ condition1 ]; then

    # Code to be executed if condition1 is true

elif [ condition2 ]; then

    # Code to be executed if condition1 is false and condition2 is true

else

    # Code to be executed if both condition1 and condition2 are false

fi

Q. Can you provide an example of a nested if statement in Bash?

Sure, here’s an example of a nested if statement in Bash:

if [ condition1 ]; then

    if [ condition2 ]; then

        # Code to be executed if both condition1 and condition2 are true

    else

        # Code to be executed if condition1 is true but condition2 is false

    fi

else

    # Code to be executed if condition1 is false

fi

In this example, the nested if statement allows you to check for additional conditions within the original if statement.

Q. How can I check if a string variable meets a specific condition in a Bash script?

You can check if a string variable meets a specific condition using the following syntax: 

if [ "$string_variable" = "desired_value" ]; then

    # Code for when the string variable is equal to "desired_value"

else

    # Code for when the string variable is not equal to "desired_value"

fi

Q. What are the basic Bash commands used in conditional statements?

The basic Bash commands essential for constructing conditional statements include:

  • if, elif, and else for checks.
  • test and [ ] for evaluating conditions.
  • [[ ]] for advanced conditional testing.
  • && and || for logical operations.

Q. How does the if-else mechanism work in bash scripting?

The if-else mechanism in Bash scripting allows the execution of a code block based on a specific condition. 

If the first condition (after the if statement) is met, the corresponding code block is executed; otherwise, the code in the else clause is executed. 

This mechanism provides a way to handle different scenarios based on conditional testing.

Q. What is the role of the root user in Bash programming and Linux system administration?

The root user, the superuser, has administrative privileges in the Linux system. 

In bash scripting and Linux system administration, the root user can execute commands and access files and directories restricted from regular users. This level of access is crucial for performing system-level tasks and configurations.

Q. How can I create a Bash script that checks whether a number is less than a specific value?

You can create a Bash script to check whether a number is less than a specific value using the following code:

#!/bin/bash

number=5

threshold=10

if [ "$number" -lt "$threshold" ]; then

    echo "Number is less than the threshold."

else

    echo "Number is greater than or equal to the threshold."

fi

In this example, the script checks if the number is less than the threshold using the -lt operator.

Q. What are some common conditional statements frequently used in Bash scripting?

Some common conditional statements frequently used in Bash scripting are:

  • if-elif-else statements.
  • case statements.
  • nested if statements.

These conditional statements are essential for controlling the execution flow in Bash scripts based on various conditions.

Q. Can you summarize the steps for using if-elif-else statements in Bash scripting?

Here’s a comprehensive guide for using if-elif-else statements in Bash scripting

  1. Start with if and a condition in square brackets or using the test command.
  2. Optionally, include elif for additional conditions.
  3. Use else for the final fallback code.
  4. End with fi

This way, you can create effective conditional logic in your Bash scripts.

Try this guide with our instant dedicated server for as low as 40 Euros