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:
- The outer
ifstatement checks if the variableageis greater than 18. If the condition is true, it executes the code block inside the firstifstatement. - Within the first
ifstatement, there is an innerifstatement that checks if the variablegradeis equal to “A”. If the condition is true, it executes the code block inside the secondifstatement. If the condition is false, it executes the code block following theelsekeyword.
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.