Read standard input until EOF.
Preserve leading and trailing spaces and backslashes in each line.
Which loop header is appropriate?
while IFS= read -r line; do ...; done preserves whitespace and backslashes while reading one line at a time; read fails at EOF.
Detailed explanation
for line in read; doIncorrect. This is not syntax for iterating input lines.
Incorrect. This is not syntax for iterating input lines.
while read line; doIncorrect. Without IFS= and -r, whitespace and backslashes may be changed.
Incorrect. Without IFS= and -r, whitespace and backslashes may be changed.
while IFS= read -r line; doCorrect. This is the standard safe line-reading loop.
Correct. This is the standard safe line-reading loop.
if IFS= read -r line; thenIncorrect. if handles one condition and does not loop to EOF.
Incorrect. if handles one condition and does not loop to EOF.
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
- EOF makes read fail and ends the loop
Notes
- Environment: POSIX sh / パイプ入力
- 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.