0
0
Bash Scriptingscripting~5 mins

Reading files line by line (while read) in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
APrevents backslash escapes from being interpreted
BReads raw binary data
CReads only the first word of the line
DReads the file in reverse order
Which command correctly reads a file line by line without losing variable values after the loop?
Awhile read line; do ... done <<< "$(cat file.txt)"
Bcat file.txt | while read line; do ... done
Cwhile read line; do ... done < file.txt
Dfor line in $(cat file.txt); do ... done
What is the purpose of setting IFS= before read?
ATo split the line into words
BTo ignore empty lines
CTo convert tabs to spaces
DTo preserve leading and trailing spaces in the line
Which of these is a common mistake when reading lines with read?
ANot redirecting the file into the loop and using a pipe instead
BUsing <code>read -r</code> to prevent backslash escapes
CUsing <code>IFS=</code> to preserve spaces
DUsing a variable to store each line
What does this script print?
while read -r line; do echo "$line"; done < file.txt
ANothing, it has a syntax error
BEach line of file.txt printed exactly as is
CThe file content reversed
DOnly the first word of each line
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.