Advanced Conditional Logic with Nested If and Logical Operators
While the basic "if-then-else" structure is powerful, Bash also provides more advanced conditional logic capabilities. By nesting "if" statements and utilizing logical operators, you can create complex decision-making processes within your shell scripts.
Nested If Statements
Nested "if" statements allow you to create a hierarchy of conditions, where the execution of one block of code depends on the evaluation of multiple conditions. This can be particularly useful when you need to make decisions based on a series of checks.
Here's an example of nested "if" statements:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ]; then
echo "The number is positive."
if [ $num -lt 100 ]; then
echo "The number is less than 100."
else
echo "The number is greater than or equal to 100."
fi
else
echo "The number is non-positive."
fi
In this example, the script first checks if the number is greater than 0. If it is, the script then checks if the number is less than 100. Depending on the outcome of these nested conditions, the script will print the appropriate message.
Logical Operators in Conditional Checks
Bash also allows you to use logical operators, such as &&
(AND), ||
(OR), and !
(NOT), to combine multiple conditions within a single "if" statement. This can help you create more complex and flexible conditional logic.
Here's an example using logical operators:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ] && [ $num -lt 100 ]; then
echo "The number is positive and less than 100."
elif [ $num -ge 100 ] || [ $num -lt 0 ]; then
echo "The number is either greater than or equal to 100, or negative."
else
echo "The number is zero."
fi
In this example, the script first checks if the number is both positive and less than 100. If this condition is true, the script prints the appropriate message. If the first condition is false, the script then checks if the number is either greater than or equal to 100, or less than 0. If this condition is true, the script prints the corresponding message. If both conditions are false, the script prints "The number is zero."
By combining nested "if" statements and logical operators, you can create highly sophisticated conditional logic in your Bash scripts, allowing you to handle complex decision-making processes.