0
0
Bash Scriptingscripting~10 mins

Iterating over arrays in Bash Scripting - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print each element of the array.

Bash Scripting
arr=(apple banana cherry)
for item in [1]; do
  echo "$item"
done
Drag options to blanks, or click blank then click option'
A${arr[@]}
B$arr
C${arr}
D$arr[@]
Attempts:
3 left
💡 Hint
Common Mistakes
Using $arr instead of ${arr[@]} which only gives the first element.
Using ${arr} which does not expand all elements.
Using $arr[@] which is incorrect syntax.
2fill in blank
medium

Complete the code to get the length of the array.

Bash Scripting
arr=(dog cat mouse)
length=[1]
echo "Length is $length"
Drag options to blanks, or click blank then click option'
A${arr}
B${arr[@]}
C${#arr[@]}
D${#arr}
Attempts:
3 left
💡 Hint
Common Mistakes
Using ${#arr} which gives length of first element string, not array length.
Using ${arr[@]} which expands elements, not length.
3fill in blank
hard

Fix the error in the code to correctly iterate over the array elements.

Bash Scripting
fruits=(mango orange pineapple)
for fruit in [1]; do
  echo "$fruit"
done
Drag options to blanks, or click blank then click option'
A$fruits
B${fruits}
C$fruits[@]
D${fruits[@]}
Attempts:
3 left
💡 Hint
Common Mistakes
Using $fruits which only gives first element.
Using $fruits[@] which is invalid syntax.
4fill in blank
hard

Fill both blanks to create an array and print its elements using a loop.

Bash Scripting
my_array=([1])
for element in [2]; do
  echo "$element"
done
Drag options to blanks, or click blank then click option'
A"red" "green" "blue"
B${my_array}
C${my_array[@]}
Dmy_array
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting array elements causing word splitting.
Using ${my_array} which only expands first element.
5fill in blank
hard

Fill all three blanks to create an array, get its length, and print each element.

Bash Scripting
colors=([1])
count=[2]
echo "Total colors: $count"
for color in [3]; do
  echo "$color"
done
Drag options to blanks, or click blank then click option'
A"yellow" "purple" "cyan"
B${#colors[@]}
C${colors[@]}
D${colors}
Attempts:
3 left
💡 Hint
Common Mistakes
Using unquoted elements causing word splitting.
Using ${colors} instead of ${colors[@]} in the loop.
Using ${#colors} which gives length of first element string.