0
0
Bash Scriptingscripting~10 mins

for loop (list-based) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - for loop (list-based)
Start
Define list
Pick first item
Execute loop body
More items?
NoEnd loop
Yes
Pick next item
Back to Execute loop body
The loop picks each item from the list one by one and runs the commands inside the loop for each item.
Execution Sample
Bash Scripting
items=(apple banana cherry)
for item in "${items[@]}"
do
  echo "$item"
done
This script loops over a list of fruits and prints each fruit on its own line.
Execution Table
Iterationitem valueActionOutput
1applePrint itemapple
2bananaPrint itembanana
3cherryPrint itemcherry
--No more items, exit loop-
💡 All items processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
itemundefinedapplebananacherrycherry
Key Moments - 3 Insights
Why does the loop stop after the last item?
The loop checks if there are more items in the list. When no items remain (see last row in execution_table), it stops.
What if the list is empty?
If the list is empty, the loop body never runs because there are no items to pick, so no output is produced.
Why do we use "${items[@]}" instead of just "$items"?
Using "${items[@]}" expands each list element separately, so the loop gets each item individually. Using "$items" would treat the whole list as one string.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'item' during iteration 2?
Abanana
Bapple
Ccherry
Dundefined
💡 Hint
Check the 'item value' column in the second row of the execution_table.
At which iteration does the loop stop running?
AAfter iteration 1
BAfter iteration 3
CAfter iteration 2
DIt never stops
💡 Hint
Look at the exit_note and the last row in execution_table.
If the list was empty, what would the output be?
Aapple banana cherry
BError message
CNo output
DLoop runs once with empty item
💡 Hint
Refer to the key_moments explanation about empty lists.
Concept Snapshot
for item in "${items[@]}"; do
  commands using $item
 done

- Loops over each item in the list
- Runs commands once per item
- Stops after last item
- Use "${items[@]}" to get each element separately
Full Transcript
This visual shows how a bash for loop works with a list. The loop starts by defining a list of items. Then it picks the first item and runs the commands inside the loop body using that item. It repeats this for each item in the list. When there are no more items, the loop stops. The variable 'item' changes each iteration to the current list element. If the list is empty, the loop does not run at all. Using "${items[@]}" ensures each item is handled separately. This is a simple way to repeat actions for each element in a list in bash scripting.