Iterating over arrays in Bash Scripting - Time & Space Complexity
When we run a script that goes through each item in a list, it takes some time. We want to understand how this time changes as the list gets bigger.
The question is: How does the work grow when we look at more items?
Analyze the time complexity of the following code snippet.
# Define an array
arr=(apple banana cherry date elderberry)
# Loop through each element
for item in "${arr[@]}"; do
echo "$item"
done
This script prints each fruit name from the array one by one.
- Primary operation: The
forloop that goes through each item in the array. - How many times: Once for every element in the array.
As the array gets bigger, the script prints more items, so it takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the array.
[X] Wrong: "The loop runs in constant time no matter how many items there are."
[OK] Correct: Each item needs to be handled once, so more items mean more work and more time.
Understanding how loops grow with input size is a key skill. It helps you explain your code clearly and shows you know how to think about efficiency.
"What if we nested another loop inside to compare each item with every other item? How would the time complexity change?"
Practice
fruits?Solution
Step 1: Understand array iteration syntax
In Bash, to iterate over all elements of an array safely, you use"${array[@]}"which expands each element as a separate word, preserving spaces.Step 2: Check each option's correctness
for fruit in "${fruits[@]}"; do echo "$fruit"; done uses"${fruits[@]}"correctly. Options B and C omit quotes or use${fruits}or${fruits[*]}without quotes, which can break elements with spaces. for fruit in fruits; do echo "$fruit"; done treatsfruitsas a string, not an array.Final Answer:
for fruit in "${fruits[@]}"; do echo "$fruit"; done -> Option CQuick Check:
Use "${array[@]}" to iterate safely [OK]
- Not quoting "${array[@]}" causing word splitting
- Using ${array} instead of ${array[@]}
- Iterating over the array name as a string
colors in Bash?Solution
Step 1: Identify correct quoting for array iteration
To iterate over array elements safely, you must quote "${array[@]}" to preserve elements with spaces.Step 2: Evaluate each option
for color in "${colors[@]}"; do echo $color; done correctly uses quotes around "${colors[@]}". for color in colors; do echo $color; done treats 'colors' as a string, not an array. for color in ${colors[@]}; do echo $color; done misses quotes, risking word splitting. for color in ${colors}; do echo $color; done uses ${colors} which is incorrect for arrays.Final Answer:
for color in "${colors[@]}"; do echo $color; done -> Option DQuick Check:
Quote "${array[@]}" for safe iteration [OK]
- Forgetting quotes around "${array[@]}"
- Using array name without $ or quotes
- Using ${array} instead of ${array[@]}
names=("Alice" "Bob Smith" "Charlie")
for name in "${names[@]}"; do
echo "$name"
doneSolution
Step 1: Understand array elements and quoting
The array has three elements: "Alice", "Bob Smith", and "Charlie". Quoting "${names[@]}" preserves each element as one word, even if it contains spaces.Step 2: Trace the loop output
The loop prints each element on its own line: first "Alice", then "Bob Smith", then "Charlie".Final Answer:
Alice Bob Smith Charlie -> Option AQuick Check:
Quoted "${array[@]}" keeps elements intact [OK]
- Assuming elements split on spaces inside quotes
- Using unquoted ${array[@]} causing word splitting
- Expecting all elements on one line
items:items=("pen" "notebook" "eraser")
for i in ${items[@]}
do
echo $i
doneSolution
Step 1: Check array declaration
The array declaration is correct with parentheses and quoted elements.Step 2: Analyze the for loop iteration
The loop uses unquoted ${items[@]}, which causes word splitting. If any element had spaces, it would split incorrectly. Quoting "${items[@]}" fixes this.Final Answer:
Missing quotes around ${items[@]} causes word splitting -> Option BQuick Check:
Always quote "${array[@]}" to avoid splitting [OK]
- Not quoting array expansion in loops
- Assuming echo needs quotes for correctness here
- Misreading array declaration syntax
files containing filenames, some with spaces. You want to print only those filenames that contain the word "report". Which script correctly iterates and filters the array?Solution
Step 1: Choose correct array iteration with quoting
To handle filenames with spaces correctly, iterate using "${files[@]}" quoted. This preserves each filename as one item.Step 2: Apply filtering condition inside loop
The condition[[ $file == *report* ]]correctly checks if the filename contains "report". for file in "${files[@]}"; do if [[ $file == *report* ]]; then echo "$file"; fi; done uses this with proper quoting and iteration.Final Answer:
for file in "${files[@]}"; do if [[ $file == *report* ]]; then echo "$file"; fi; done -> Option AQuick Check:
Quote "${array[@]}" and filter inside loop [OK]
- Using unquoted ${files[@]} splitting filenames
- Using ${files[*]} which joins all elements into one string
- Iterating over literal 'files' string
Ready to prove it?
Pass the test and this pattern moves unknown
