Read standard input one line at a time while preserving leading and trailing spaces and backslashes.
Which while condition is appropriate?
IFS= read -r preserves surrounding whitespace and treats backslashes literally; quote the line variable in the loop.
Detailed explanation
while IFS= read -r line; do process "$line"; doneCorrect. Empty IFS and -r preserve the line content while it is read.
Correct. Empty IFS and -r preserve the line content while it is read.
while read line; do process $line; doneIncorrect. Default read processing and unquoted expansion can change whitespace and boundaries.
Incorrect. Default read processing and unquoted expansion can change whitespace and boundaries.
for line in $(cat); do process "$line"; doneIncorrect. Command substitution and word splitting iterate over words rather than original lines.
Incorrect. Command substitution and word splitting iterate over words rather than original lines.
read -a line | while line; do process; doneIncorrect. This is not a valid loop that reads lines.
Incorrect. This is not a valid loop that reads lines.
Try it yourself
An example you can run in a temporary verification environment.
printf ' a\\b \n' | while IFS= read -r line; do printf '<%s>\n' "$line"; doneExpected result
< a\b >Key points
- IFS= preserves whitespace
- read -r preserves backslashes
- Quote expansions
Notes
- Environment: GNU Bash 5.2 / 標準入力
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.