Read lines and NUL-separated records
For ordinary text, while IFS= read -r line; do ...; done < file reads one line at a time without trimming surrounding whitespace or interpreting backslashes. The redirection supplies the file as input to the whole loop. A final unterminated nonempty line is assigned by read but returns nonzero at EOF, so use while IFS= read -r line || [[ -n $line ]]; do ...; done when that last line must be included. This pattern assumes a normal readable text stream, not a way to diagnose all input errors. Filenames may contain newlines. In Bash, read -d '' uses the NUL byte as record delimiter; NUL cannot occur in a Unix filename. Use a NUL-terminated stream from a compatible producer (for example GNU find -print0, covered later). Do not store NUL bytes in shell variables or capture such a stream via command substitution. Quote each resulting record. The example uses fixed synthetic names and process substitution as taught earlier. The NUL-delimited example assumes every record ends in NUL. A final unterminated record may be assigned by read with a nonzero status, but the demonstrated loop does not process it. Check producer success and framing separately when completeness matters. The first two examples guard fixture creation with && before reading.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Preserve whitespace and backslashes
printf '%s\n' ' report ' 'a\b' '' > input.txt &&while IFS= read -r line; do printf '[%s]\n' "$line"done < input.txtExpected stdout:
[ report ][a\b][]Whitespace, a literal backslash, and a blank line survive.
Include the final partial line
printf 'first\nlast' > input.txt &&while IFS= read -r line || [[ -n $line ]]; do printf '[%s]\n' "$line"done < input.txtExpected stdout:
[first][last]The OR condition includes the nonempty value returned at EOF.
Read NUL-delimited names
count=0while IFS= read -r -d '' name; do count=$(( count + 1 )) printf '%q\n' "$name"done < <(printf '%s\0' 'daily report' $'two\nlines')printf 'count=%s\n' "$count"Expected stdout:
daily\ report$'two\nlines'count=2%q shows a shell-escaped representation so the embedded newline is visible; two records are read.
Common mistakes
Avoid for line in $(cat file) for reading records: splitting and globbing can change data, and command substitution removes trailing newlines. A newline is not a safe delimiter for arbitrary Unix filenames.
Practice
Create a fixture containing a padded line, an empty line and a final nonempty line without newline. Print each in brackets using the EOF-aware loop. Then feed two NUL-delimited names, one with an embedded newline, and count two records.
Next: Loop state and pipeline subshells