0
0
Bash Scriptingscripting~10 mins

if-then-fi structure in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - if-then-fi structure
Start
Evaluate condition
Execute commands inside then
End if
Skip commands inside then
End if
The script checks a condition. If true, it runs commands inside then. If false, it skips them and ends the if block.
Execution Sample
Bash Scripting
if [ "$num" -gt 0 ]; then
  echo "Positive number"
fi
Checks if num is greater than 0; if yes, prints 'Positive number'.
Execution Table
StepConditionResultBranch TakenOutput
1[ "$num" -gt 0 ]TrueExecute then blockPositive number
2End of if-Exit if-
💡 Condition false or commands inside then executed; if block ends with fi.
Variable Tracker
VariableStartAfter Step 1Final
num555
Key Moments - 2 Insights
Why does the script skip the echo command sometimes?
Because the condition in the if statement is false, so the then block is not executed (see execution_table step 1).
What does 'fi' mean in the script?
'fi' marks the end of the if block, telling the shell where the conditional commands finish.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens when the condition is true?
AThe commands inside then block are skipped
BThe commands inside then block run
CThe script ends immediately
DThe condition is checked again
💡 Hint
See execution_table row 1, 'Branch Taken' and 'Output' columns
At which step does the script finish the if block?
AStep 2
BStep 1
CBefore Step 1
DAfter Step 2
💡 Hint
Check execution_table row 2, 'Step' and 'Branch Taken' columns
If num was -3, what would happen at step 1?
ACondition true, then block runs
BScript crashes
CCondition false, then block skipped
DCondition true, but then block skipped
💡 Hint
Refer to variable_tracker for num value and execution_table step 1 condition result
Concept Snapshot
if-then-fi structure in bash:
if [ condition ]; then
  commands
fi
- Checks condition
- Runs commands if true
- Ends with fi
- Skips commands if false
Full Transcript
This visual execution shows how the bash if-then-fi structure works. The script starts by evaluating a condition inside the if statement. If the condition is true, it executes the commands inside the then block. If false, it skips those commands. The if block ends with fi. Variables like num keep their values unchanged during this process. Key points include understanding that fi marks the end of the if block and that commands inside then only run when the condition is true. The execution table traces these steps clearly, showing when commands run or are skipped.