0
0
Bash Scriptingscripting~20 mins

while loop in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of a simple while loop counting down
What is the output of this Bash script?
Bash Scripting
count=3
while [ $count -gt 0 ]
do
  echo $count
  count=$((count - 1))
done
A
3
2
1
B
3
2
1
0
C
1
2
3
D
0
1
2
3
Attempts:
2 left
💡 Hint
Remember the loop runs while count is greater than zero and decreases count each time.
💻 Command Output
intermediate
2:00remaining
While loop with a break condition
What will this Bash script output?
Bash Scripting
i=1
while true
 do
  echo $i
  if [ $i -eq 3 ]; then
    break
  fi
  i=$((i + 1))
done
A
1
2
B
1
2
3
4
C
1
2
3
D
1
2
3
4
5
Attempts:
2 left
💡 Hint
The loop breaks when i equals 3.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this while loop
Which option shows the correct syntax to fix the error in this Bash while loop?
Bash Scripting
count=5
while [ $count -gt 0 ]
  echo $count
  count=$((count - 1))
done
A
Add 'do' after the while condition:
while [ $count -gt 0 ]; do
BReplace 'done' with 'end'
CRemove the square brackets from the condition
DAdd a semicolon after 'done'
Attempts:
2 left
💡 Hint
A while loop in Bash requires a 'do' keyword after the condition.
🔧 Debug
advanced
2:00remaining
Why does this while loop run infinitely?
This script runs forever. What is the reason?
Bash Scripting
num=1
while [ $num -le 3 ]
do
  echo $num
done
AThe echo command causes the loop to restart
BVariable 'num' is never updated inside the loop
CMissing 'do' keyword after while condition
DThe condition uses '-le' which is invalid
Attempts:
2 left
💡 Hint
Check if the loop changes the variable controlling the condition.
🚀 Application
expert
3:00remaining
Create a while loop to read lines from a file
Which script correctly reads each line from 'input.txt' and prints it?
A
while read line; do
  echo $line
  done > input.txt
B
while [ read line ]; do
  echo $line
done < input.txt
C
while read line
  echo $line
done < input.txt
D
while read line; do
  echo "$line"
done < input.txt
Attempts:
2 left
💡 Hint
The 'read' command reads a line, and the loop must redirect input from the file.