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
if
statement checks if the variableage
is greater than 18. If the condition is true, it executes the code block inside the firstif
statement. - Within the first
if
statement, there is an innerif
statement that checks if the variablegrade
is equal to “A”. If the condition is true, it executes the code block inside the secondif
statement. If the condition is false, it executes the code block following theelse
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.