Overview
This lecture explains how to use the logical AND (&&) operator in Bash if statements to evaluate multiple conditions, detailing different syntactic approaches and their use cases.
Using Logical AND Operator in Bash if Statements
- The logical AND operator (&&) lets you combine multiple conditions in a Bash if statement.
- When using &&, all conditions must be true for the "then" block to execute; otherwise, the "else" block runs.
- Bash evaluates combined expressions left to right and stops at the first false condition.
Syntax Options for Multiple Conditions
- Basic syntax:
if [ EXPR1 ] && [ EXPR2 ] && [ EXPRN ]; then ... else ... fi
- Example:
[ $num -gt 10 ] && [ $num -lt 20 ] checks both conditions before executing the "then" block.
Using -a Option with Single Brackets
- The
-a flag joins multiple test expressions within a single bracket: [ EXPR1 -a EXPR2 ].
- Example:
[ $num -gt 10 -a $num -lt 20 ] is another way to combine conditions in one test.
Using Double Square Brackets
- Double brackets allow use of
&& inside: if [[ EXPR1 && EXPR2 ]]; then ... else ... fi
- Double brackets recognize comparison operators like
>, <, and support more advanced features.
- Example:
[[ $num -gt 10 && $num -lt 20 ]] checks both conditions with improved syntax.
Using Individual Double Square Brackets
- Separate double brackets allow conditions to be linked:
[[ EXPR1 ]] && [[ EXPR2 ]]
- Only evaluates the second condition if the first is true, otherwise immediately goes to "else".
Choosing an Approach
- Double brackets offer more flexibility, supporting unquoted expansions and advanced comparisons.
- For strict POSIX compatibility, prefer single brackets.
- Consistency in style is recommended for code clarity.
Key Terms & Definitions
- Logical AND (&&) — Operator that returns true if all combined conditions are true.
- -a Option — Test alias in brackets to join multiple conditions.
- Double Square Brackets ([[ ]]) — Enhanced conditional test syntax, supports advanced operators.
Action Items / Next Steps
- Practice writing Bash if statements using &&, -a, and double brackets.
- Choose and standardize one syntax style in your scripts for clarity.
- Review comparison operators and test syntax in Bash documentation.