0
0
Bash Scriptingscripting~10 mins

Logical operators (-a, -o, !) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Logical operators (-a, -o, !)
Start
Evaluate first condition
Apply -a (AND) or -o (OR) operator
If ! operator present, negate result
Final result: True or False
End
The script checks conditions, combines them with AND (-a) or OR (-o), and can negate the result with !.
Execution Sample
Bash Scripting
if [ "$x" -gt 5 -a "$y" -lt 10 ]; then
  echo "Both conditions true"
fi
Checks if x is greater than 5 AND y is less than 10, then prints a message.
Execution Table
StepCondition CheckedEvaluationOperatorCombined ResultNegation (!)Final ResultAction
1"$x" -gt 5True (x=7)-a
2"$y" -lt 10True (y=8)-aTrue AND True = TrueTrueExecute echo
3ExitNo more conditionsEnd if
💡 All conditions evaluated; combined result True; no negation; action executed.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x7777
y8888
Combined ResultN/AN/ATrueTrue
Key Moments - 2 Insights
Why do we use -a instead of && inside [ ]?
Inside [ ], -a is used for AND because && is a shell operator outside test brackets. See execution_table rows 1 and 2 where -a combines conditions.
What does the ! operator do in conditions?
The ! operator negates the condition result. If the combined result is True, ! makes it False, and vice versa. This happens after combining conditions, as shown in concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what is the combined result of the conditions?
AFalse
BTrue
CUndefined
DError
💡 Hint
Check the Combined Result column in Step 2 of execution_table.
At which step does the script decide to execute the echo command?
AStep 2
BStep 3
CStep 1
DNo echo executed
💡 Hint
Look at the Action column in execution_table rows.
If we add ! before the whole condition, what would be the final result given x=7 and y=8?
ATrue
BError
CFalse
DDepends on shell
💡 Hint
Refer to concept_flow and key_moments about negation.
Concept Snapshot
Logical operators in bash test [ ]:
-a means AND (both conditions true)
-o means OR (either condition true)
! negates the condition
Use -a and -o inside [ ], not && or ||
Negation applies after combining conditions
Full Transcript
This visual trace shows how bash logical operators -a (AND), -o (OR), and ! (NOT) work inside test brackets [ ]. The script checks each condition step-by-step, combines them with -a or -o, then optionally negates the result with !. Variables x and y are checked against numeric conditions. The combined result determines if the action inside if runs. Key points include using -a and -o inside [ ] instead of shell operators, and that ! negates the final combined result. The execution table tracks each step, condition evaluation, and final decision.