0
0
Bash Scriptingscripting~20 mins

Iterating over arrays in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of iterating over a bash array with spaces
What is the output of this bash script?
Bash Scripting
arr=("apple" "banana split" "cherry")
for item in "${arr[@]}"; do
  echo "$item"
done
A
apple
banana split
cherry
B
apple
banana
split
cherry
Capple banana split cherry
D
apple
banana split cherry
Attempts:
2 left
💡 Hint
Think about how double quotes affect array expansion in bash loops.
💻 Command Output
intermediate
2:00remaining
Iterating over array indices in bash
What does this script output?
Bash Scripting
arr=(10 20 30)
for i in "${!arr[@]}"; do
  echo "$i:${arr[i]}"
done
ASyntax error
B
10:10
20:20
30:30
C
0:10
1:20
2:
D
0:10
1:20
2:30
Attempts:
2 left
💡 Hint
${!arr[@]} gives the indices of the array.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in array iteration
Which option contains a syntax error when iterating over a bash array?
Bash Scripting
arr=(a b c)
Afor i in ${arr[*]}; do echo $i; done
Bfor i in "${arr[@]}"; do echo $i; done
Cfor i in ${arr[)}; do echo $i; done
Dfor i in ${arr[@]}; do echo $i; done
Attempts:
2 left
💡 Hint
Check how arrays are expanded in bash.
💻 Command Output
advanced
2:00remaining
Output when iterating over array with unquoted expansion
What is the output of this script?
Bash Scripting
arr=("one two" three)
for i in ${arr[@]}; do
  echo "$i"
done
A
one two
three
B
one
two
three
Cone two three
DSyntax error
Attempts:
2 left
💡 Hint
Unquoted expansion splits elements on spaces.
🚀 Application
expert
3:00remaining
Count total words from all array elements in bash
Given an array with elements containing multiple words, which script correctly counts the total number of words across all elements?
Bash Scripting
arr=("hello world" "foo bar baz" "single")
A
count=0
for i in "${arr[@]}"; do
  count=$((count + $(echo "$i" | wc -w)))
done
 echo $count
B
count=0
for i in "${arr[@]}"; do
  count=$((count + 1))
done
 echo $count
C
count=0
for i in ${arr[@]}; do
  count=$((count + 1))
done
 echo $count
D
count=0
for i in ${arr[@]}; do
  count=$((count + $(echo "$i" | wc -w)))
done
 echo $count
Attempts:
2 left
💡 Hint
Use quotes to preserve elements and count words inside each element.