0
0
Bash Scriptingscripting~10 mins

C-style for loop in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - C-style for loop
Initialize variable
Check condition
Execute body
Update variable
Back to Check condition
The loop starts by setting a variable, then checks a condition. If true, it runs the loop body, updates the variable, and repeats. If false, it stops.
Execution Sample
Bash Scripting
for ((i=0; i<3; i++)); do
  echo $i
done
This loop prints numbers 0, 1, and 2 by increasing i from 0 to 2.
Execution Table
Iterationi (before check)Condition (i<3)Body executedOutputi (after update)
10TrueYes01
21TrueYes12
32TrueYes23
43FalseNo
💡 i reaches 3, condition 3<3 is False, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i<3 becomes false at iteration 4 (see execution_table row 4), so the loop does not run the body again.
When is the variable i updated in the loop?
i is updated after the loop body executes in each iteration (see execution_table column 'i (after update)').
What happens if the initial value of i is already 3?
The condition i<3 is false immediately, so the loop body never runs (like iteration 4 in the table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i before the condition check in iteration 3?
A2
B3
C1
D0
💡 Hint
Check the 'i (before check)' column in row 3 of the execution_table.
At which iteration does the loop condition become false?
AIteration 2
BIteration 3
CIteration 4
DIteration 1
💡 Hint
Look at the 'Condition (i<3)' column and find where it is False.
If we change the loop to for ((i=0; i<=3; i++)), how many times will the loop body execute?
A3 times
B4 times
C5 times
D2 times
💡 Hint
Think about the condition i<=3 and compare with the variable_tracker values.
Concept Snapshot
C-style for loop syntax in bash:
for (( init; condition; update )); do
  commands
 done

- init runs once at start
- condition checked before each iteration
- loop runs while condition is true
- update runs after each iteration
- useful for counting loops
Full Transcript
A C-style for loop in bash scripting starts by initializing a variable, then checks a condition before each loop run. If the condition is true, the loop body runs, then the variable updates. This repeats until the condition is false. For example, 'for ((i=0; i<3; i++))' prints 0, 1, and 2. The loop stops when i reaches 3 because the condition i<3 is no longer true. The variable i changes after each loop body execution. If i starts at 3, the loop never runs because the condition is false from the start.