0
0
Bash Scriptingscripting~5 mins

Iterating over arrays in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an array in Bash scripting?
An array in Bash is a list of values stored in a single variable. You can access each value by its position number, starting at zero.
Click to reveal answer
beginner
How do you write a simple for loop to iterate over all elements in a Bash array named fruits?
Use: <br>for fruit in "${fruits[@]}"; do<br> echo "$fruit"<br>done<br>This prints each fruit in the array one by one.
Click to reveal answer
beginner
What does ${array[@]} mean in Bash?
It means all elements of the array. When used in a loop, it lets you access each item one by one.
Click to reveal answer
beginner
How can you get the number of elements in a Bash array named colors?
Use ${#colors[@]}. It returns the count of items in the array.
Click to reveal answer
intermediate
Why is it important to quote "${array[@]}" when iterating over arrays in Bash?
Quoting preserves each element as a single item, even if it contains spaces. Without quotes, elements with spaces may split into multiple words.
Click to reveal answer
Which syntax correctly iterates over all elements in a Bash array named items?
Afor item in "${items[@]}"; do echo "$item"; done
Bfor item in ${items}; do echo "$item"; done
Cfor item in ${items[@]}; do echo $item; done
Dfor item in items; do echo "$item"; done
How do you get the length of a Bash array named my_array?
A${#my_array[@]}
B${my_array.length}
Clength(my_array)
Dcount(my_array)
What happens if you forget to quote "${array[@]}" in a for loop?
AThe loop will not run
BElements with spaces may split into multiple words
CThe array will be empty
DIt causes a syntax error
Which of these is a valid way to declare an array in Bash?
Aarray = {apple, banana, cherry}
Barray = [apple, banana, cherry]
Carray = (apple banana cherry)
Darray=(apple banana cherry)
How do you access the first element of a Bash array named list?
Alist[0]
B${list[1]}
C${list[0]}
Dlist(0)
Explain how to iterate over all elements in a Bash array and print each element.
Think about how you loop over a list of items in real life, like reading names from a list.
You got /4 concepts.
    Describe why quoting array expansions is important when iterating over arrays in Bash.
    Imagine reading a list where some names have spaces, like 'New York'.
    You got /3 concepts.