0
0
Bash Scriptingscripting~10 mins

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

Choose your learning style9 modes available
Concept Flow - if-elif-else
Start
Check if condition1
|Yes
Execute block1
End
No
Check if condition2
|Yes
Execute block2
End
No
Execute else block
End
The script checks the first condition; if true, it runs its block and ends. Otherwise, it checks the next condition(s). If none match, it runs the else block.
Execution Sample
Bash Scripting
num=7
if [ $num -lt 5 ]; then
  echo "Less than 5"
elif [ $num -eq 7 ]; then
  echo "Equal to 7"
else
  echo "Other number"
fi
This script checks if num is less than 5, equal to 7, or something else, then prints a message.
Execution Table
StepCondition CheckedCondition ResultBranch TakenOutput
1[ $num -lt 5 ]FalseNo
2[ $num -eq 7 ]TrueYesEqual to 7
3elseN/ANo
💡 Condition [ $num -eq 7 ] is True, so the elif block runs and script ends.
Variable Tracker
VariableStartAfter Execution
num77
Key Moments - 2 Insights
Why does the script not print "Less than 5" even though it checks that condition first?
Because the condition [ $num -lt 5 ] is False (num is 7), so the script skips that block and checks the next condition as shown in step 1 and 2 of the execution_table.
What happens if none of the if or elif conditions are true?
The else block runs, as it is the fallback. This is shown in step 3 of the execution_table where else would execute if previous conditions were False.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
AEqual to 7
BLess than 5
COther number
DNo output
💡 Hint
Check the 'Output' column in row for step 2 in execution_table.
At which step does the script decide to run the elif block?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Branch Taken' column and see where condition is True for elif.
If num was 3, how would the execution table change?
AStep 2 condition True, output 'Equal to 7'
BStep 3 else runs
CStep 1 condition True, output 'Less than 5', no further checks
DNo output at all
💡 Hint
Refer to variable_tracker and imagine num=3, then check condition results in execution_table.
Concept Snapshot
if-elif-else in bash:
if [ condition1 ]; then
  commands
elif [ condition2 ]; then
  commands
else
  commands
fi

Checks conditions in order; runs first true block; else runs if none true.
Full Transcript
This visual execution shows how bash if-elif-else works. The script starts by checking the first condition. If it is true, it runs that block and ends. If false, it checks the next condition. If none are true, it runs the else block. In the example, num=7 is checked against less than 5 (false), then equal to 7 (true), so it prints 'Equal to 7' and stops. Variables stay the same during checks. This helps beginners see exactly how conditions are tested and which block runs.