Facebook X (Twitter) Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook X (Twitter) Instagram
    TecAdmin
    You are at:Home»Programming»Bash Shell»Bash if elif else Statement: A Comprehensive Tutorial

    Bash if elif else Statement: A Comprehensive Tutorial

    By RahulApril 12, 20234 Mins Read

    In this comprehensive tutorial, we will delve into the Bash if elif else statement, a crucial control structure in shell scripting. Bash, an acronym for Bourne-Again SHell, is a Unix shell and command-line interpreter that has become the default shell for many Linux distributions and macOS. Mastering the if elif else statement will greatly enhance your ability to write efficient and flexible shell scripts.

    1. Understanding Bash if elif else Statement

    The if elif else statement is a control structure that allows you to execute a block of code based on whether a given condition is true or false. It provides a way to make decisions within your shell script and perform different actions based on the outcome of these decisions. The if statement checks a condition, while the elif (short for “else if”) and else clauses provide alternative code blocks to execute when the initial condition is false.

    2. Basic Syntax of Bash if elif else Statement

    The general syntax for the if elif else statement in Bash is as follows:

    1
    2
    3
    4
    5
    6
    7
    if [CONDITION]; then
      # Code block to execute if CONDITION is true
    elif [ANOTHER_CONDITION]; then
      # Code block to execute if ANOTHER_CONDITION is true
    else
      # Code block to execute if all previous conditions are false
    fi

    3. Bash if Statement

    3.1 Simple if Statement

    The simplest form of the if statement checks a single condition and executes a block of code only when the condition is true.

    Example:

    1
    2
    3
    4
    5
    6
    7
    #!/bin/bash
     
    number=10
     
    if [ $number -eq 10 ]; then
      echo "The number is equal to 10."
    fi

    This script checks if a given number is equal to 10 and prints a message if the condition is true.

    3.2 if-else Statement

    The if-else statement checks a condition and executes one block of code when the condition is true and another block when the condition is false.

    Example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/bin/bash
     
    number=5
     
    if [ $number -gt 10 ]; then
      echo "The number is greater than 10."
    else
      echo "The number is not greater than 10."
    fi

    This script checks if a given number is greater than 10, prints a message if the condition is true, and prints an alternative message if the condition is false.

    4. Bash elif Statement

    The elif clause provides a way to test multiple conditions sequentially. When using elif, the first condition that evaluates to true will execute its associated code block, and the rest will be skipped.

    Example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #!/bin/bash
     
    number=15
     
    if [ $number -lt 10 ]; then
      echo "The number is less than 10."
    elif [ $number -eq 10 ]; then
      echo "The number is equal to 10."
    else
      echo "The number is greater than 10."
    fi

    This script checks if a given number is less than, equal to, or greater than 10, and prints an appropriate message based on the evaluation.

    5. Combining Conditions with AND and OR Operators

    You can use the logical AND (-a or &&) and logical OR (-o or ||) operators to combine conditions in your if statements.

    Example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/bin/bash
     
    number=25
     
    if [ $number -gt 10 ] && [ $number -lt 20 ]; then
      echo "The number is between 10 and 20."
    else
      echo "The number is not between 10 and 20."
    fi

    This script checks if a given number is between 10 and 20 using the AND operator, and prints a message based on the evaluation.

    6. Testing Multiple Conditions with elif

    You can use multiple elif clauses to test a series of conditions in sequence. If any condition evaluates to true, its associated code block will execute, and the rest of the conditions will be skipped.

    Example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #!/bin/bash
     
    number=45
     
    if [ $number -lt 20 ]; then
      echo "The number is less than 20."
    elif [ $number -ge 20 ] && [ $number -lt 40 ]; then
      echo "The number is between 20 and 40."
    elif [ $number -ge 40 ] && [ $number -lt 60 ]; then
      echo "The number is between 40 and 60."
    else
      echo "The number is greater than or equal to 60."
    fi

    This script checks if a given number falls within different specified ranges, and prints a message based on the evaluation.

    7. Nested if Statements

    You can use nested if statements to create more complex decision-making structures in your shell scripts. This involves placing an if statement within another if statement.

    Example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    #!/bin/bash
     
    number=15
     
    if [ $(($number % 2)) -eq 0 ]; then
      echo "The number is even."
      if [ $(($number % 4)) -eq 0 ]; then
        echo "The number is also divisible by 4."
      else
        echo "The number is not divisible by 4."
      fi
    else
      echo "The number is odd."
      if [ $(($number % 3)) -eq 0 ]; then
        echo "The number is also divisible by 3."
      else
        echo "The number is not divisible by 3."
      fi
    fi

    This script checks if a given number is even or odd using an if-else statement. Inside each branch, a nested if-else statement checks if the number is divisible by 4 (if even) or divisible by 3 (if odd), and prints appropriate messages based on the evaluations.

    8. Practical Examples

    Let’s look at a few practical examples of using if elif else statements in Bash shell scripts.

    Example 1: User input validation

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/bin/bash
     
    read -p "Enter a number between 1 and 10: " number
     
    if [ $number -ge 1 ] && [ $number -le 10 ]; then
      echo "Valid input."
    else
      echo "Invalid input. Please enter a number between 1 and 10."
    fi

    This script prompts the user to enter a number between 1 and 10, validates the input, and prints a message based on the validation result.

    Example 2: File existence check

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/bin/bash
     
    file_path="example.txt"
     
    if [ -f "$file_path" ]; then
      echo "The file exists."
    else
      echo "The file does not exist."
    fi

    This script checks if a specified file exists and prints a message based on the file’s existence.

    Conclusion

    The Bash if elif else statement is a powerful control structure that allows you to create complex decision-making processes in your shell scripts. Understanding and using this statement effectively will greatly enhance your ability to write efficient and flexible scripts. Practice using different conditions, operators, and nesting techniques to become proficient in using the Bash if elif else statement.

    elif else if then
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Calculate difference between two dates in Bash

    Checking If a Command Succeeded in Bash Using the `$?` Special Variable

    How to Generate Random String in Bash

    View 3 Comments

    3 Comments

    1. Eben on June 19, 2020 3:32 pm

      How would I combine commands in a code block? Is it done using indentation like in Python?

      Reply
    2. Deon on February 22, 2018 11:07 am

      Thank you for the examples.

      I’m trying to build a backup bash script that also save progress to a log file and later send an email to confirm success or failure.

      All the backup parts work, but my IF fails. If first looked at using $? to check for success, but sqldump creates a file even if the DB is not accessible. Now I’m trying to check of file size using $du -k file_name | cut -f 1 and this works giving the file size. The issue is the if do not seem to work.

      if ($actualsize -gt $minsize) then
      echo “bla bla bla” >> /var/log/backup.log
      else
      echo “bla bla” >> /var/log/backup.log
      fi

      I would also like to have an error counter as I’m backup multiple DB’s and folders.

      Any advice?

      Reply
      • Rahul K. on February 23, 2018 4:18 am

        Hi Deon, You are using wrong braces in if condition. Also use ; when using then in same line. Hope this helps you.

        if [ $actualsize -gt $minsize ]; then
        echo “bla bla bla” >> /var/log/backup.log
        else
        echo “bla bla” >> /var/log/backup.log
        fi

        Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Difference Between Full Virtualization vs Paravirtualization
    • Virtualization vs. Containerization: A Comparative Analysis
    • Using .env Files in Django
    • Using .env File in FastAPI
    • Setting Up Email Notifications for Django Error Reporting
    Facebook X (Twitter) Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.