Recall & Review
beginner
What does the
while read loop do in bash scripting?It reads a file line by line, assigning each line to a variable for processing inside the loop.
Click to reveal answer
intermediate
How do you safely read lines with spaces or special characters using
while read?Use
IFS= before read to preserve leading/trailing spaces and special characters.Click to reveal answer
intermediate
Why is it better to use
while read instead of cat file | while read?Using
while read with input redirection avoids creating a subshell, so variables set inside the loop remain accessible after it ends.Click to reveal answer
beginner
What happens if you don't use
IFS= when reading lines with read?The
read command trims leading/trailing spaces and splits the line on spaces or tabs, which can change the original line content.Click to reveal answer
beginner
Show a simple bash script snippet to read a file named
data.txt line by line and print each line.while read -r line; do
echo "$line"
done < data.txt
Click to reveal answer
What does the
-r option do in read -r?✗ Incorrect
The
-r option tells read not to treat backslashes as escape characters, preserving them literally.Which command correctly reads a file line by line without losing variable values after the loop?
✗ Incorrect
Redirecting the file into the while loop (
done < file.txt) avoids subshells, so variables set inside remain after the loop.What is the purpose of setting
IFS= before read?✗ Incorrect
Setting
IFS= disables word splitting, so the entire line including spaces is read as-is.Which of these is a common mistake when reading lines with
read?✗ Incorrect
Using a pipe creates a subshell, so variables set inside the loop are lost after it ends.
What does this script print?
while read -r line; do echo "$line"; done < file.txt
✗ Incorrect
The script reads each line safely with
-r and prints it exactly as it appears in the file.Explain how to read a file line by line in bash using
while read and why it is useful.Think about how you would read a list of names one at a time.
You got /4 concepts.
Describe the role of
IFS= and -r options when reading lines with read.Consider how spaces and backslashes might change the line if not handled.
You got /3 concepts.