Introduction
Iterating over arrays lets you do something with each item in a list, like checking or printing them one by one.
array=(item1 item2 item3) for element in "${array[@]}"; do # commands using $element echo "$element" done
fruits=(apple banana cherry) for fruit in "${fruits[@]}"; do echo "$fruit" done
empty_array=() for item in "${empty_array[@]}"; do echo "$item" done
single_item=(onlyone) for element in "${single_item[@]}"; do echo "$element" done
words=("hello world" "foo bar" "baz") for word in "${words[@]}"; do echo "$word" done
#!/bin/bash # Create an array of colors colors=(red green blue yellow) # Print all colors before loop printf "Colors before loop: %s\n" "${colors[*]}" # Iterate over the array and print each color for color in "${colors[@]}"; do echo "Color: $color" done # Print all colors after loop printf "Colors after loop: %s\n" "${colors[*]}"
fruits?"${array[@]}" which expands each element as a separate word, preserving spaces."${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 treats fruits as a string, not an array.colors in Bash?names=("Alice" "Bob Smith" "Charlie")
for name in "${names[@]}"; do
echo "$name"
doneitems:items=("pen" "notebook" "eraser")
for i in ${items[@]}
do
echo $i
donefiles 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?[[ $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.Pass the test and this pattern moves unknown