0
0
Bash Scriptingscripting~20 mins

Reading files line by line (while read) in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Line Reader Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
What is the output of this script reading a file line by line?
Consider a file named colors.txt with the following content:
red
green
blue

What will be the output of this script?
while read line; do
echo "$line"
done < colors.txt
Bash Scripting
while read line; do
echo "$line"
done < colors.txt
A
red
green
blue
Bred green blue
C
eulb
neerg
der
D
ed
green
blue
Attempts:
2 left
💡 Hint
Think about how read reads each line and how echo prints it.
💻 Command Output
intermediate
2:00remaining
What happens if you use a pipe with while read loop?
Given the same colors.txt file, what will this script output?
cat colors.txt | while read line; do
echo "$line"
done
Bash Scripting
cat colors.txt | while read line; do
echo "$line"
done
Ared green blue
B
red
green
blue
CNo output
D
eulb
neerg
der
Attempts:
2 left
💡 Hint
Pipes send the file content to the loop line by line.
💻 Command Output
advanced
2:00remaining
What error occurs with this incorrect while read syntax?
What error or output results from running this script?
while read line
  echo "$line"
done < colors.txt
Bash Scripting
while read line
  echo "$line"
done < colors.txt
ASyntax error: 'do' expected
BPrints all lines correctly
CNo output
DRuntime error: file not found
Attempts:
2 left
💡 Hint
Check the syntax for the while loop in bash.
🚀 Application
advanced
2:00remaining
How to count lines in a file using while read loop?
Which script correctly counts the number of lines in colors.txt using a while read loop?
A
count=0
while read line; do
  count=$count + 1
done &lt; colors.txt
echo $count
B
count=0
while read line; do
  count++
done &lt; colors.txt
echo $count
C
count=0
while read line; do
  count=$((count + 1))
done &lt; colors.txt
echo $count
D
count=0
while read line; do
  let count+1
done &lt; colors.txt
echo $count
Attempts:
2 left
💡 Hint
Use arithmetic expansion $(( )) to increment variables in bash.
🧠 Conceptual
expert
2:00remaining
Why does this while read loop skip the last line sometimes?
Consider this script:
while read line; do
echo "$line"
done < file.txt

If file.txt does not end with a newline character, what happens to the last line and why?
AAll lines print correctly regardless of newline
BThe last line is printed twice due to buffering
CThe script crashes with an error about missing newline
DThe last line is skipped because read expects a newline to finish reading a line
Attempts:
2 left
💡 Hint
Think about how the read command detects line endings.