How to Use Bash Conditional Statements

Updated on October 4, 2024
How to Use Bash Conditional Statements header image

Introduction

Conditional statements are programming constructs that execute specific blocks of commands when a condition evaluates to true or false to control the execution flow. A conditional statement in Bash uses expressions to evaluate the result before returning a true or false value to execute the succeeding commands.

This article explains how to use bash conditional statements including if, if-else, case, and if/elif/else statements.

Bash Conditional Statements

Bash supports multiple types of conditional statements:

  • If: Executes a block of commands if a condition is true.
  • If-else: Executes a block of commands if a condition is true and an alternative block of commands if the condition is false.
  • Case: Tests an expression or variable against multiple patterns and executes the commands associated with the first matching pattern.
  • If/elif/else: Sequentially checks multiple conditions and runs the commands matching the first condition that evaluates to true.

Conditional Expressions

Conditional expressions compare values and execute specific commands based on the result. The test command evaluates whether a condition is true or false. You can use the [ and [[ operators to run the test command and perform string or arithmetic comparisons and evaluate the result of specific conditions.

Conditional expressions use the following operators depending on the type of condition or operation in a statement.

Numeric Operators

Numeric operators in Bash compare numeric values and return true or false based on the result. Numeric operators evaluate the relationship between arithmetic values in conditional expressions as follows:

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

For example:

[ 1 -eq 1 ]

The above condition tests if 1 is equals to 1.

Logical Operators

Logical operators in Bash compare multiple values in a condition and return true or false depending on the result. Logical operators evaluate the relationship between two or more commands or variables as follows:

  • -a: Logical AND.
  • -o: Logical OR.
  • !: Negation.
  • &&: AND executes the second command if the first command succeeds.
  • ||: OR executes the second command whether the first command fails or succeeds.

For example:

[ 1 -eq 1 ] && [ 2 -eq 2 ]

In the above example, both expressions must be successful to return a zero exit status or a non-zero status in case of failure.

String Operators

In Bash, string operators compare strings and return true or false depending on the condition's result. String operators evaluate the character length or relationship between two or more strings in a condition as follows:

  • =: Equal to.
  • !=: Not equal to.
  • <: Less than (lexicographically).
  • >: Greater than (lexicographically).

For example:

[ "a" != "a" ]

The above test compares the strings and returns true if the strings are not equal (!=).

File Operators

File operators in Bash test file properties like existence, status, and permissions and return true or false based on the result. You can use conditional expressions and file operators to check the contents and attributes of one or more files as follows:

  • -e: File exists.
  • -f: The file is a regular file.
  • -d: A directory.
  • -r: The File is readable.
  • -w: The File is writable.
  • -x: The File is executable.

For example:

[ -f /etc/hosts ]

The above test returns true if the /etc/hosts file is available.

Exit Status Operators

Exit status operators check the exit status of commands to determine if they succeeded or failed. The exit status code is a numeric value where 0 represents a success, and any non-zero value, such as 1, represents a failure. Status codes apply in expressions and test if a specific operation is successful or not.

  • $?: Stores the exit status of the last executed command.
  • !: Negates the exit status and returns true if a command fails.

For example:

[ $? -eq 0 ]

The above test returns true if the previous command is successful and a zero 0 exit status code.

Use Conditional Statements in Bash

Conditional statements in shell scripts use expressions to evaluate commands or operations before executing specific commands. If the condition is true, the associated commands run. If the condition is false, alternative commands run or are skipped if no match is found.

For example:

  • If statement:

    bash
    #!/bin/bash
    
    if [ 1 -eq 1 ]; 
    then
        echo "1 is equal to 1"
    fi
    
  • If-else statement:

    bash
    #!/bin/bash
    
    if [ 1 -eq 1 ]; 
    then
        echo "1 is equal to 1"
    else
        echo "1 is not equal to 1"
    fi
    
  • Case-statement:

    bash
    #!/bin/bash
    
    var=1
    
    case "$var" in
        1)
            echo "The value is valid"
            ;;
        2)
            echo "The value does not match"
            ;;
        *)
            echo "Try another value"
            ;;
    esac
    
  • If-elif statement:

    bash
    #!/bin/bash
    
    if [ 1 -eq 1 ]; 
    then
        echo "1 is equal to 1"
    elif [ 1 -gt 0 ];
    then
    echo "1 is greater than 0"
    else
        echo "1 is not equal to 1"
    fi
    

Nested Conditional Statements

Nested conditional statements evaluate a condition multiple times until a match is found. Nested statements support different types of conditional statements at various levels to filter and generate a final result.

For example:

bash
#!/bin/bash

value=1

case $value in
    1)
        echo "Value is 1"
        if [ 1 -eq 1 ]; then
            echo " 1 is equal to 1"
        elif [ 1 -gt 0 ]; then
            echo " 1 is greater than 0"
        else
            echo " 1 is not equal to 1"
        fi
        ;;
    2)
        echo "Value is 2"
        if [ 2 -eq 2 ]; then
            echo " 2 is equal to 2"
        elif [ 2 -lt 1 ]; then
            echo " 2 is less than 1"
        else
            echo " 2 is not less than 1"
        fi
        ;;
    *)
        echo "Value is neither 1 nor 2"
        if [ $value -eq 0 ]; then
            echo " Value is 0"
        elif [ $value -lt 0 ]; then
            echo " Value is less than 0"
        else
            echo " Value is neither 0 nor less than 0"
        fi
        ;;
esac

The above nested conditional statement uses a case block to test if the value variable matches any pattern. In each pattern, a nested if-elif-else block filters the final result to execute the succeeding commands to display a message.

Conclusion

You can use Bash conditional statements to efficiently test conditions and execute a specific block of commands if the condition evaluates to true or false. Conditional statements can also be integrated with loops and functions to continuously execute specific commands in a Bash shell environment or script.