0
0
Bash Scriptingscripting~10 mins

if-then-else in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - if-then-else
Start
Evaluate condition
Execute THEN block
End
Execute ELSE block
End
The script checks a condition. If true, it runs the THEN part; if false, it runs the ELSE part, then ends.
Execution Sample
Bash Scripting
if [ "$num" -gt 10 ]; then
  echo "Greater than 10"
else
  echo "10 or less"
fi
Checks if variable num is greater than 10 and prints a message accordingly.
Execution Table
StepConditionCondition ResultBranch TakenOutput
1[ "$num" -gt 10 ]TrueTHENGreater than 10
2End of if-then-else---
💡 Condition true, THEN branch executed, script ends.
Variable Tracker
VariableStartAfter Step 1Final
num151515
Key Moments - 2 Insights
Why does the script run the THEN block and not the ELSE block when num is 15?
Because at Step 1 in the execution_table, the condition [ "$num" -gt 10 ] is True, so the THEN branch is taken.
What happens if the condition is false?
If the condition is false, the ELSE block runs instead, as shown in the concept_flow where the No branch leads to ELSE execution.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at Step 1 when num=15?
AGreater than 10
B10 or less
CNo output
DError
💡 Hint
Check the Output column in execution_table row for Step 1.
At which step does the script decide which branch to take?
ABefore Step 1
BStep 2
CStep 1
DAfter Step 2
💡 Hint
Look at the Condition and Branch Taken columns in execution_table.
If num was 5 instead of 15, which branch would run?
ATHEN branch
BELSE branch
CBoth branches
DNo branch
💡 Hint
Refer to concept_flow and key_moments about condition false leading to ELSE.
Concept Snapshot
if [ condition ]; then
  # commands if true
else
  # commands if false
fi

Checks condition once.
Runs THEN block if true.
Runs ELSE block if false.
Ends after one branch runs.
Full Transcript
This visual execution shows how a bash if-then-else works. The script starts and evaluates the condition. If the condition is true, it runs the THEN block commands. If false, it runs the ELSE block commands. Then the script ends. For example, if the variable num is 15, the condition checking if num is greater than 10 is true, so the THEN block runs and prints 'Greater than 10'. If num was 5, the ELSE block would run and print '10 or less'. This helps decide between two paths based on a condition.