BudiBadu Logo
Samplebadu

Bash by Example: Nested Conditionals

Bash 5.0+

Using elif for multiple condition branches and nested if blocks for complex decision trees, implementing multi-level conditionals without deep indentation, choosing between elif chains and case statements for readability, and avoiding common pitfalls in nested conditional logic.

Code

#!/bin/bash

score=85

if [ $score -ge 90 ]; then
    echo "Grade: A"
elif [ $score -ge 80 ]; then
    echo "Grade: B"
    if [ $score -ge 85 ]; then
        echo " (High B)"
    fi
elif [ $score -ge 70 ]; then
    echo "Grade: C"
else
    echo "Grade: F"
fi

Explanation

When dealing with complex decision logic, you often need more than a simple if-else structure. Bash provides the elif (else if) keyword, allowing you to chain multiple conditions together. The script checks each condition in order and executes the block for the first one that evaluates to true.

You can also nest if statements inside any block (then, elif, or else) to create hierarchical logic. This is useful for refining decisions, such as checking a secondary condition only after a primary condition has been met.

Proper indentation is crucial for readability when nesting conditionals. Although Bash does not enforce indentation like Python, using a consistent 2 or 4 space indent helps you visually track the nesting levels and ensures your code remains maintainable.

Code Breakdown

7
elif stands for "else if". It provides a way to check a new condition if the previous if statement was false. You can have as many elif blocks as needed.
9
A nested if statement inside the elif block. This code is only executed if the score is between 80 and 89, and then it further checks if the score is 85 or higher.
14
The else block acts as a catch-all. If none of the preceding if or elif conditions are true, the code in this block is executed.
16
fi marks the end of the entire if-elif-else structure. Every if must have a corresponding fi.