Skip to content
shellhacks.dev
Shell Scripting

Read a File Line by Line in POSIX sh with read

Read a file line by line in POSIX sh with while IFS= read -r line. A last line without a newline is skipped unless the loop also tests that line is not empty.

1 min read
Summarize in AI

A loop reads a file and drops the last line, or eats the leading spaces and backslashes of the others.

Shell
printf '  indented\nback\\slash\nlast without newline' > in.txt
while IFS= read -r line; do printf '[%s]\n' "$line"; done < in.txt
echo ---
while IFS= read -r line || [ -n "$line" ]; do printf '[%s]\n' "$line"; done < in.txt
Text
[  indented]
[back\slash]
---
[  indented]
[back\slash]
[last without newline]

Setting IFS to empty for the read keeps leading and trailing whitespace, and -r stops it treating a backslash as an escape, as in the read utility specification. The first loop shows the remaining problem: read returns non-zero when it hits the end of input before a newline, so the loop ends without running for the last line even though the variable was filled. Testing the variable as a second condition runs the body once more.

A line with a NUL byte cannot be held in a shell variable at all. Commands inside the loop that read standard input will consume the file, so give them < /dev/null or read the file on another descriptor with read -r line <&3.

Share

More snippets

Shell Scripting

Return Text from a Function in POSIX sh

A POSIX sh function returns text by printing it, and the caller captures the output with command substitution. Variables set inside are lost, and trailing newlines go.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.