0
0
Bash Scriptingscripting~20 mins

for loop (list-based) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
1:30remaining
Output of a simple list-based for loop
What is the output of this Bash script?
Bash Scripting
for item in apple banana cherry; do
  echo $item
 done
Aapple banana cherry
B
item
item
item
C
apple
banana
cherry
DSyntax error
Attempts:
2 left
💡 Hint
Remember that the loop runs once for each item in the list and echo prints each item on a new line.
💻 Command Output
intermediate
1:30remaining
Counting items in a list with a for loop
What is the value of the variable count after running this script?
Bash Scripting
count=0
for word in one two three four; do
  count=$((count + 1))
done
echo $count
ASyntax error
B4
C1
D0
Attempts:
2 left
💡 Hint
The loop increments count once for each word in the list.
💻 Command Output
advanced
2:00remaining
Output of nested for loops with lists
What is the output of this Bash script?
Bash Scripting
for i in 1 2; do
  for j in a b; do
    echo "$i$j"
  done
done
A
1a
1b
2a
2b
B
1 2
a b
C1a 1b 2a 2b
DSyntax error
Attempts:
2 left
💡 Hint
The outer loop runs twice, and for each iteration the inner loop runs twice.
💻 Command Output
advanced
2:00remaining
Effect of quotes in list-based for loop
What is the output of this Bash script?
Bash Scripting
for item in "one two" three; do
  echo "$item"
done
A
"one two"
three
B
one
two
three
CSyntax error
D
one two
three
Attempts:
2 left
💡 Hint
Quotes group words together as a single item in the list.
💻 Command Output
expert
2:30remaining
Output of for loop with command substitution and word splitting
What is the output of this Bash script?
Bash Scripting
for file in $(echo "file1.txt file2.txt"); do
  echo "$file"
done
A
file1.txt
file2.txt
B"file1.txt file2.txt"
Cfile1.txt file2.txt
DSyntax error
Attempts:
2 left
💡 Hint
Command substitution outputs a string that is split into words for the loop.