0
0
Bash Scriptingscripting~10 mins

Iterating over arrays in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Iterating over arrays
Define array
Start loop: for each element
Access current element
Execute commands with element
Next element?
YesRepeat loop
No
End loop
This flow shows how a bash script defines an array, then loops over each element to run commands, repeating until all elements are processed.
Execution Sample
Bash Scripting
arr=(apple banana cherry)
for fruit in "${arr[@]}"; do
  echo "$fruit"
done
This script loops over each fruit in the array and prints it.
Execution Table
IterationVariable fruitActionOutput
1applePrint fruitapple
2bananaPrint fruitbanana
3cherryPrint fruitcherry
--Loop endsAll elements processed
💡 All elements in the array have been iterated, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
fruitundefinedapplebananacherrycherry
Key Moments - 2 Insights
Why do we use "${arr[@]}" instead of just "${arr}" in the loop?
Using "${arr[@]}" expands to all elements separately, so the loop iterates over each item. Using "${arr}" would treat the whole array as one string, causing only one iteration. See execution_table rows 1-3 where each fruit is printed separately.
What happens if the array is empty?
The loop body does not execute at all because there are no elements to iterate. The exit_note confirms the loop ends immediately with no output.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'fruit' during iteration 2?
Aapple
Bcherry
Cbanana
Dundefined
💡 Hint
Check the 'Variable fruit' column in execution_table row for iteration 2.
At which iteration does the loop stop iterating over the array?
AAfter iteration 2
BAfter iteration 3
CAfter iteration 1
DNever stops
💡 Hint
Look at the exit_note and the last iteration number in execution_table.
If we change the array to arr=(dog cat), how many iterations will the loop run?
A2
B3
C1
D0
💡 Hint
Refer to variable_tracker and execution_table to see how iterations relate to array length.
Concept Snapshot
Bash array iteration:
Define array: arr=(item1 item2 ...)
Loop: for var in "${arr[@]}"; do ... done
Each loop var holds one element
Use "${arr[@]}" to expand all elements
Loop ends after last element
Full Transcript
This lesson shows how to loop over arrays in bash scripting. First, you define an array with multiple items. Then, you use a for loop with "${arr[@]}" to access each element one by one. Inside the loop, you can run commands using the current element. The loop repeats until all elements are processed. Using "${arr[@]}" is important because it expands each element separately. If the array is empty, the loop does not run. The example prints each fruit in the array on its own line.