Bash / Intermediate: reliable data and failure paths / Lesson 14
Read records while preserving state and content
Choose a line-reading contract that preserves backslashes and parent-shell state while acknowledging producer status boundaries.
On this page
Lesson goals
- Read line-oriented input without unwanted trimming.
- Keep loop state in the intended shell.
- Handle a final unterminated line and producer failures deliberately.
- Preserve line contents and parent-shell state under an explicit record contract.
- Observe producer completion separately from the consuming loop.
Specify the record format
A line-oriented format is useful only when a newline cannot occur inside one logical record, or when an escaping convention is defined. Decide whether blank lines are records, whether a final line may lack a newline, and whether leading or trailing whitespace matters. Filenames can contain newlines, so line-oriented examples are not a universal filename transport. Use NUL-delimited interfaces when both tools support them and arbitrary filenames must be preserved.
Read without losing content
Setting IFS empty for read prevents its usual field trimming, and -r prevents backslashes from being interpreted as escapes. The loop also processes a nonempty final value if read reaches end of file without a terminating newline. The example uses a here-string for compact synthetic input; here-strings supply a newline, so test an actual unterminated file separately. Quote the value when printing it to preserve its contents.
input=$'first line\nsecond line\nlast line'
while IFS= read -r line || [[ -n $line ]]; do
printf "record=<%s>\n" "$line"
done <<< "$input"
IFS and -r preserve ordinary line contents; the extra condition handles a nonempty unterminated final line.
Keep state in the parent shell
A loop placed in a pipeline may run in a subshell, depending on shell context and settings, so its variable updates may not be visible afterward. Redirecting process substitution into the loop allows this example’s loop to update count in the current shell. The producer runs separately. The displayed count demonstrates the parent state, but it does not establish whether the producer succeeded.
count=0
while IFS= read -r line; do
((count += 1))
done < <(printf "%s\n" alpha beta)
printf "count=%s\n" "$count"
Redirection keeps this loop in the current shell; producer status requires separate handling.
Own the producer outcome
Process substitution provides a data stream, not an automatic guarantee that the loop’s exit status represents the producer’s status. If producer failure matters, choose an explicit method to capture and wait for that producer or materialize output in an owned temporary file and check the command before reading it. Avoid deleting files the script did not create. Define cleanup and partial-output behavior before using this pattern for operational work.
Verify exact records and status
Test empty input, a blank line, leading and trailing spaces, backslashes, and a final line without a newline. Compare the number and exact contents of records, not merely the script’s final status. Test producer failure independently and verify that the chosen status channel exposes it. For a filename workflow, add a filename containing a newline and confirm that a NUL-delimited design preserves it without changing unrelated files.
Define the line-record contract
A line-oriented interface uses newline as a record delimiter only when the payload cannot contain an unescaped newline or the format defines an escaping rule. Decide whether blank lines count as records, whether leading and trailing spaces matter, and whether a final record may lack its terminating newline. These decisions determine the correct loop and expected count. An empty stream and a single blank line are different inputs.
A filename can contain a newline, so one line per filename is not a universal pathname transport. Where arbitrary Unix filenames must be preserved, choose a NUL-delimited producer and consumer that both support the interface. Bash variables cannot store embedded NUL bytes, so consume one non-NUL pathname payload at a time rather than capturing the entire stream in a scalar.
Preserve record contents
IFS= read -r line is a common form for literal line payloads. The empty IFS prevents read from trimming edge whitespace, and -r prevents backslashes from being treated as escapes. read consumes the delimiter rather than storing it. Quote "$line" when forwarding or printing the value so spaces and wildcard characters do not change the argument list. A blank line is a successful read with an empty payload.
A plain while read condition can skip an unterminated final fragment: read assigns the characters but returns nonzero at EOF without the delimiter. If the contract permits a nonempty fragment, an alternate condition such as || [[ -n $line ]] processes it once. If the delimiter is required, report malformed input instead. A here-string supplies a newline, so it cannot alone prove handling of a truly unterminated file.
Keep the loop in the intended shell
A loop on the right side of a pipeline may execute in a subshell environment, leaving a counter incremented there unchanged in the parent. Test the value after the loop under the target Bash settings; do not infer persistence from a line printed inside the loop. lastpipe can affect the final stage under documented conditions, so avoid an undeclared reliance on an interactive option.
Redirecting a file or process-substitution endpoint into the loop can keep the loop itself in the current shell. A count of two after reading alpha and beta then persists in the parent. The producer of process substitution still runs separately, so persistent state says nothing by itself about whether that producer completed successfully. Data ownership and status observation must be designed together.
Observe producer completion independently
Process substitution supplies a stream but does not automatically make the producer’s failure the consuming loop’s status. A producer may emit a line and return nonzero while the loop reads that line and terminates successfully. If the application requires complete input, arrange an explicit status and wait protocol for the owned producer or run it as a separately checked stage.
A private temporary file can make a bounded two-stage design straightforward: create the owned directory, run the producer into its file, check the producer status, and only then read the verified file in the current shell. Remove only the owned temporary directory and define what happens to partial output on failure. Do not publish a count or result as complete merely because the consumer reached EOF.
Verify contents, state and failure
Use controlled fixtures for empty input, a blank line, edge spaces, a literal backslash and an allowed or rejected unterminated final record. Assert exact record count and contents as well as the parent variable after the loop. For a pathname workflow, test a synthetic filename containing a newline with a supported NUL-delimited interface in an isolated directory.
Inject a producer failure after partial output and check that the chosen status channel exposes it. Verify that rejected or incomplete input does not trigger publication or unrelated side effects. Keep stdout and diagnostics separate and clean up only resources created by the test. A successful loop status, a persistent counter and a complete producer are three distinct claims that require their own evidence.
20 worked examples
1. Preserve spaces and backslashes
Problem: Read a synthetic line with edge spaces and a backslash.
- Empty IFS avoids trimming the spaces and -r preserves the backslash.
- The newline delimiter is consumed while the quoted output retains the whole payload.
IFS= read -r line < <(printf "%s\n" ' path\name ')
printf "<%s>\n" "$line"
< path\name >
Why this result follows: Empty IFS avoids trimming the spaces and -r preserves the backslash.
2. Accept a final fragment
Problem: Process an allowed nonempty final record without a newline.
- The second read assigns last but returns nonzero at EOF without a delimiter.
- The nonempty-fragment condition admits last once after the terminated first record.
count=0
while IFS= read -r line || [[ -n $line ]]; do count=$((count + 1)); printf "%s:<%s>\n" "$count" "$line"; done < <(printf "first\nlast")
1:<first>
2:<last>
Why this result follows: The second read assigns last but returns nonzero at EOF without a delimiter.
3. Keep a parent counter
Problem: Count two lines through process-substitution input.
- The redirected loop executes in the current shell and reads two synthetic lines.
- Both increments remain visible in the parent counter after the loop.
count=0
while IFS= read -r line; do count=$((count + 1)); done < <(printf "alpha\nbeta\n")
printf "%s\n" "$count"
2
Why this result follows: The redirected loop executes in the current shell and reads two synthetic lines.
4. Observe a child counter
Problem: Run a pipe-fed loop with lastpipe disabled.
- With lastpipe disabled, the pipeline loop updates a subshell copy of count.
- The parent’s original counter remains zero after the successful child loop.
shopt -u lastpipe
count=0
printf "alpha\nbeta\n" | while IFS= read -r line; do count=$((count + 1)); done
printf "%s\n" "$count"
0
Why this result follows: With lastpipe disabled, the pipeline loop updates a subshell copy of count.
5. Expose partial producer output
Problem: Count one line from a separately failing producer.
- The loop reads the partial line and completes normally while the producer returns nonzero separately.
- The observed count and loop status do not prove that production succeeded.
count=0
while IFS= read -r line; do count=$((count + 1)); done < <(printf "partial\n"; false)
printf "count=%s loop=%s\n" "$count" "$?"
count=1 loop=0
Why this result follows: The loop reads the partial line and completes normally while the producer returns nonzero separately.
6. Count empty input
Problem: Count records when a producer emits nothing.
- The producer supplies neither a newline delimiter nor a nonempty final fragment.
- The loop body never runs, so the parent counter remains zero.
count=0
while IFS= read -r line || [[ -n $line ]]; do count=$((count + 1)); done < <(:)
printf "%s\n" "$count"
0
Why this result follows: The producer supplies neither a newline delimiter nor a nonempty final fragment.
7. Count a blank line
Problem: Treat one newline as one empty record.
- The newline terminates one successful read whose payload is empty.
- The loop displays the empty record once and increments count to one.
count=0
while IFS= read -r line; do count=$((count + 1)); printf "<%s>\n" "$line"; done < <(printf "\n")
printf "count=%s\n" "$count"
<>
count=1
Why this result follows: The newline terminates one successful read whose payload is empty.
8. Show here-string termination
Problem: Observe the newline supplied by a here-string.
- The here-string supplies a newline after the input text.
- read therefore finds a delimiter and returns zero; this is not an unterminated-file test.
input=last
IFS= read -r line <<< "$input"
status=$?
printf "%s|%s\n" "$line" "$status"
last|0
Why this result follows: The here-string supplies a newline after the input text.
9. Reject a missing final delimiter
Problem: Detect a nonempty final fragment when the format requires a newline.
- read assigns last but returns nonzero after reaching EOF without a newline.
- The explicit format policy reports the missing delimiter rather than accepting the fragment.
IFS= read -r line < <(printf "last")
status=$?
if (( status != 0 )) && [[ -n $line ]]; then printf "missing delimiter\n"; fi
missing delimiter
Why this result follows: read assigns last but returns nonzero after reaching EOF without a newline.
10. Read a verified private file
Problem: Check a producer before counting its temporary output.
- The producer completes successfully before the current-shell loop reads its private output file.
- The loop counts two lines and the trap removes only the owned temporary directory.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
producer() { printf "alpha\nbeta\n"; }
if producer > "$tmp/input"; then count=0; while IFS= read -r line; do count=$((count + 1)); done < "$tmp/input"; printf "%s\n" "$count"; else exit 1; fi
2
Why this result follows: The producer completes successfully before the current-shell loop reads its private output file.
11. Reject failed staged production
Problem: Do not count partial output after a producer returns failure.
- The producer writes partial data but returns status seven.
- The else branch captures that failure and does not enter the success path that would consume it.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
producer() { printf "partial\n"; return 7; }
if producer > "$tmp/input"; then printf "unexpected\n"; else status=$?; printf "producer=%s\n" "$status"; fi
producer=7
Why this result follows: The producer writes partial data but returns status seven.
12. Preserve a leading tab
Problem: Read a tab-prefixed line without trimming.
- Empty IFS prevents read from trimming the leading tab.
- Bash printf %q displays the retained tab in a readable shell representation.
IFS= read -r line < <(printf "\tvalue\n")
printf "%q\n" "$line"
$'\tvalue'
Why this result follows: Empty IFS prevents read from trimming the leading tab.
13. Preserve a wildcard payload
Problem: Print a record containing a literal asterisk.
- The read assigns the asterisk as record data.
- The quoted later expansion prevents it from becoming a filename pattern.
IFS= read -r line < <(printf "*\n")
printf "<%s>\n" "$line"
<*>
Why this result follows: The read assigns the asterisk as record data.
14. Read an empty middle record
Problem: Process a blank line between two nonempty lines.
- Each newline terminates one record, including the empty middle payload.
- The loop counts and displays all three records in order.
count=0
while IFS= read -r line; do count=$((count + 1)); printf "%s:<%s>\n" "$count" "$line"; done < <(printf "a\n\nb\n")
1:<a>
2:<>
3:<b>
Why this result follows: Each newline terminates one record, including the empty middle payload.
15. Read NUL-delimited names
Problem: Read two synthetic pathname payloads separated by NUL.
- The empty -d delimiter tells Bash read to consume each NUL-delimited payload.
- The current-shell loop preserves both distinct names and the count two.
count=0
while IFS= read -r -d "" name; do count=$((count + 1)); printf "<%s>\n" "$name"; done < <(printf "one\0two\0")
printf "count=%s\n" "$count"
<one>
<two>
count=2
Why this result follows: The empty -d delimiter tells Bash read to consume each NUL-delimited payload.
16. Preserve a newline in a pathname
Problem: Read a synthetic pathname payload containing a newline.
- The NUL byte, rather than the internal newline, terminates this record.
- The quoted value retains the embedded newline within one pair of markers.
IFS= read -r -d "" name < <(printf "first\nsecond\0")
printf "<%s>\n" "$name"
<first
second>
Why this result follows: The NUL byte, rather than the internal newline, terminates this record.
17. Count records from a verified file
Problem: Keep a loop in the parent after a successful staging step.
- Input redirection reads the private file without placing the loop in a pipeline.
- Both increments remain in the parent and the owned fixture is removed at exit.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
printf "a\nb\n" > "$tmp/input"
count=0
while IFS= read -r line; do count=$((count + 1)); done < "$tmp/input"
printf "parent=%s\n" "$count"
parent=2
Why this result follows: Input redirection reads the private file without placing the loop in a pipeline.
18. Preserve a final backslash
Problem: Read a record ending with a literal backslash.
- The -r option prevents the final backslash from escaping the delimiter.
- The stored payload retains the backslash and the newline is consumed.
IFS= read -r line < <(printf "%s\n" 'path\')
printf "<%s>\n" "$line"
<path\>
Why this result follows: The -r option prevents the final backslash from escaping the delimiter.
19. Observe delimiter removal
Problem: Measure a simple stored line after read.
- read stores the three payload characters but not the terminating newline.
- The resulting string abc therefore has length three.
IFS= read -r line < <(printf "abc\n")
printf "%s\n" "${#line}"
3
Why this result follows: read stores the three payload characters but not the terminating newline.
20. Do not publish a failed count
Problem: Keep a synthetic publication flag false after producer failure.
- The controlled producer returns five and selects the failure branch.
- The publication flag remains no, so the failure is not represented as a completed result.
producer() { return 5; }
published=no
if producer; then published=yes; else status=$?; printf "status=%s " "$status"; fi
printf "published=%s\n" "$published"
status=5 published=no
Why this result follows: The controlled producer returns five and selects the failure branch.
Common errors and fixes
Leading spaces disappear
- Why it happens
- read used its default field splitting behavior.
- How to fix it
- Set IFS empty for the read operation and use -r.
- Prevent it next time
- Test leading and trailing whitespace and backslashes.
A loop counter is zero afterward
- Why it happens
- The loop ran in a subshell created by a pipeline.
- How to fix it
- Use an appropriate redirection or explicitly return the result.
- Prevent it next time
- Test the parent variable after the loop in the target Bash environment.
Producer failure is reported as success
- Why it happens
- The loop status was treated as the status of process substitution.
- How to fix it
- Capture the producer outcome through an explicit owned channel.
- Prevent it next time
- Inject producer failure and assert the script’s documented result.
20 practice exercises
1. Does process substitution automatically make producer failure the loop status?
Show hint
Process substitution supplies a stream from separately running work.
Show worked solution
No. It supplies the input stream, while the producer executes separately. If its status matters, arrange to capture and wait for it or check a materialized temporary output before reading.
No. The loop’s status does not automatically become the producer’s status. Coordinate and wait for the owned producer or check a staged temporary output before reading when completeness matters.
Check your solution
- Loop and producer statuses are distinguished.
- Producer completion is checked explicitly.
2. Why is a line format insufficient for arbitrary filenames?
Show hint
A newline can occur inside one filename.
Show worked solution
A filename can contain a newline, so one filename can appear as multiple lines. Use a NUL-delimited producer and consumer where supported, and test a name containing a newline in an isolated directory.
A newline-delimited list can split one filename into several apparent records. Use a NUL-delimited producer and consumer where supported, and test a newline-containing name in an isolated directory.
Check your solution
- An embedded newline is not treated as a safe separator.
- The supported NUL-delimited boundary is tested.
3. A record contains leading and trailing spaces. How should read preserve them?
Show hint
Set IFS empty for the read.
Show worked solution
Use IFS= read -r line for the declared line-oriented input and quote "$line" when using it. The empty IFS prevents the usual edge-whitespace trimming for that read.
Check your solution
- Leading and trailing spaces are retained
- The later value expansion is quoted
4. A record contains path\name. Why is read -r appropriate?
Show hint
The -r option controls backslash interpretation.
Show worked solution
read -r preserves the backslash literally instead of treating it as an escape. Test the exact payload and use a fixed printf format when displaying it.
Check your solution
- The backslash remains in the payload
- The output format treats the record as data
5. A stream contains a single newline and no other bytes. How many records are there?
Show hint
A delimiter can terminate an empty payload.
Show worked solution
There is one empty record, so a line loop should execute once with an empty value. This is different from an empty stream, which produces no record.
Check your solution
- One record is counted
- The record payload is empty
6. An empty stream feeds a loop whose count starts at zero. What should remain afterward?
Show hint
No delimiter or fragment is present.
Show worked solution
The body runs zero times and the parent count remains zero when the loop runs in the current shell. Test this separately from a blank-line record.
Check your solution
- The loop executes zero times
- The retained count is zero
7. Input first followed by newline and last without newline is allowed. How can both records be processed?
Show hint
A nonempty final fragment needs an explicit condition.
Show worked solution
Use a loop condition such as IFS= read -r line || [[ -n $line ]] and process the final fragment once. Verify that the loop does not invent an extra empty record.
Check your solution
- first and last are processed once each
- No extra empty record is added
8. The format requires a final newline, but input ends in last without one. What should happen?
Show hint
The missing delimiter violates the contract.
Show worked solution
Detect the nonzero read status with a nonempty fragment and report malformed input. Do not silently accept the fragment under a contract that requires termination.
Check your solution
- The missing delimiter is diagnosed
- The malformed fragment is not accepted as complete
9. Why can a here-string test fail to demonstrate an unterminated final line?
Show hint
A here-string supplies a newline.
Show worked solution
A here-string appends a newline, so read can succeed on the supplied value. Use an actual controlled stream or file lacking the final delimiter to test that case.
Check your solution
- The here-string newline is recognized
- An actual unterminated fixture is tested
10. With lastpipe disabled, a pipe-fed loop increments count twice. What does its parent observe?
Show hint
The pipeline loop runs in a subshell environment.
Show worked solution
The parent observes its original count because the loop updated a child copy. If the parent needs the count, choose a current-shell redirection or an explicit returned aggregate.
Check your solution
- The child performs the increments
- The parent counter remains unchanged
11. A loop reads alpha and beta through input redirection in the current shell. What count remains?
Show hint
The loop itself stays in the current shell.
Show worked solution
The two successful reads increment the parent count to two, which remains visible after the loop. Check the producer or staged input independently before treating the count as complete.
Check your solution
- The parent count is two
- Input completeness is checked separately
12. Does < <(producer) make the producer’s nonzero status the loop status automatically?
Show hint
The producer and loop are separate execution contexts.
Show worked solution
No. Process substitution supplies input while the producer runs separately. Arrange explicit coordination or use a separately checked staging step when producer failure matters.
Check your solution
- The loop status is not assumed to be the producer status
- Producer completion is observed separately
13. A producer prints partial then returns 7, while a loop counts one line and returns zero. Is the count complete?
Show hint
The producer failed after emitting data.
Show worked solution
No. The count describes the line consumed, not a complete successful production. Preserve and report status seven through an explicit channel before publishing a result.
Check your solution
- Partial output is recognized
- Producer status seven blocks a complete result
14. How can an owned temporary file make producer status visible before a loop reads?
Show hint
Check the producer as a separate stage.
Show worked solution
Create a private directory, run the producer into its file and check its status before reading. On failure, handle the partial file according to policy and clean only the owned directory.
Check your solution
- The producer status is checked before reading
- Only owned temporary state is cleaned
15. A producer fails after writing a partial staged file. Should the success branch count it?
Show hint
Required production did not complete.
Show worked solution
No. Capture the producer’s failure and avoid treating the staged partial file as complete input. Clean or retain it only according to the documented recovery policy.
Check your solution
- The producer failure is preserved
- The partial file is not accepted as complete
16. Why is a line-oriented list insufficient for arbitrary Unix filenames?
Show hint
A filename may itself contain a newline.
Show worked solution
A newline inside a filename can appear to be a record boundary and split one name into multiple apparent records. Use a supported NUL-delimited interface for arbitrary pathnames.
Check your solution
- An embedded newline is recognized as possible data
- The chosen interface preserves filename boundaries
17. A NUL-delimited pathname contains an internal newline. What should read -r -d "" preserve?
Show hint
NUL, not newline, is the record delimiter.
Show worked solution
It reads one non-NUL pathname payload and preserves the internal newline as data. The NUL delimiter is consumed and is not stored in the Bash variable.
Check your solution
- The newline remains within one payload
- The NUL delimiter is consumed
18. Can a Bash scalar store an entire NUL-delimited stream without loss?
Show hint
Bash variables cannot retain embedded NUL bytes.
Show worked solution
No. Consume individual non-NUL pathname payloads or use a binary-capable tool instead of capturing the full stream into one variable. Check producer completion separately.
Check your solution
- Embedded NUL is not assumed stored
- Producer completion remains separate
19. What should a regression test assert for a line-reading interface?
Show hint
Content, state and status are distinct outcomes.
Show worked solution
Assert exact records and count, the parent state after the loop, and the producer’s completion status. Include empty, blank, spaced, backslash and final-fragment cases.
Check your solution
- Record contents and parent state are asserted
- Producer failure is tested separately
20. A file has the bytes a newline newline b without a final newline. A loop uses IFS= read -r line || [[ -n $line ]] and increments count each iteration. Predict the count and identify each record.
Show hint
An empty line is a record; the final nonempty fragment needs the second condition.
Show worked solution
The count is 3: the records are a, an empty string, and b. The first two reads succeed at newline delimiters, including the blank line. The last read reaches EOF and returns nonzero but assigns b, so the nonempty test admits that final fragment once.
Check your solution
- The loop counts 3 records, including the blank record
- The final b is processed once despite its missing newline
Key takeaways
- Define record boundaries and preserve text deliberately.
- Treat producer status and parent-shell state as separate contracts.
- IFS= read -r preserves edge whitespace and backslashes.
- A persistent counter does not prove producer success.
- A final unterminated record requires an explicit policy.