Nested If statements in bash

In Bash, you can nest if statements within each other to create more complex conditions and decision-making structures. This allows you to evaluate multiple conditions in a hierarchical manner. Here’s an example of nested if statements in Bash:

#!/bin/bash

age=25
grade="A"

if [ "$age" -gt 18 ]; then
    echo "You are an adult."
    if [ "$grade" == "A" ]; then
        echo "Congratulations! You have achieved excellent grades."
    else
        echo "Your grades are not excellent."
    fi
else
    echo "You are not yet an adult."
fi

In this example, there are two levels of if statements:

  1. The outer if statement checks if the variable age is greater than 18. If the condition is true, it executes the code block inside the first if statement.
  2. Within the first if statement, there is an inner if statement that checks if the variable grade is equal to “A”. If the condition is true, it executes the code block inside the second if statement. If the condition is false, it executes the code block following the else keyword.

When you run this script, it will output:

You are an adult.
Congratulations! You have achieved excellent grades.

Nested if statements allow you to create more intricate conditional logic by evaluating multiple conditions in a hierarchical manner. You can nest if statements as deeply as required to suit your specific script requirements. Just ensure proper indentation and structure to maintain readability.

Leave a Comment

Your email address will not be published. Required fields are marked *