Bird
0
0

What is the correct way to iterate over all elements in a Bash array named fruits?

easy🧠 Conceptual Q11 of 15
Bash Scripting - Arrays
What is the correct way to iterate over all elements in a Bash array named fruits?
Afor fruit in ${fruits[*]}; do echo "$fruit"; done
Bfor fruit in ${fruits}; do echo "$fruit"; done
Cfor fruit in "${fruits[@]}"; do echo "$fruit"; done
Dfor fruit in fruits; do echo "$fruit"; done
Step-by-Step Solution
Solution:
  1. 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.
  2. 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 treats fruits as a string, not an array.
  3. Final Answer:

    for fruit in "${fruits[@]}"; do echo "$fruit"; done -> Option C
  4. Quick Check:

    Use "${array[@]}" to iterate safely [OK]
Quick Trick: Always quote "${array[@]}" to handle spaces safely [OK]
Common Mistakes:
MISTAKES
  • Not quoting "${array[@]}" causing word splitting
  • Using ${array} instead of ${array[@]}
  • Iterating over the array name as a string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes