A report can be neatly sorted and still be wrong. It might select the wrong field, lose repeated owners or contain partial output from a failed pipeline. This lesson connects a small report to every source record and preserves the distinction between valid emptiness and failure.
You will build a complete Bash owner-report script from the conditions, quoting and pipeline rules already taught. Then adapt a complete starter to report statuses from a second dataset. No loop, function or new runtime is needed.
1. Define the input and output before writing the script
Complete Check input and return a useful status and settle its cleanup. The earlier delimited-record lesson introduced this same simple three-field contract:
| Position | Meaning | Rule |
|---|---|---|
| 1 | Record ID | One nonempty value without a comma. |
| 2 | Status | One nonempty lowercase status without a comma. |
| 3 | Owner | One nonempty value without a comma. |
Each record has exactly three fields separated by two commas and ends in a newline. There is no header, blank record, extra field, embedded comma, CSV quoting or multiline field. Spaces can belong to a field, but commas cannot. A zero-byte file is a valid dataset with zero records; it is different from a file containing one blank line.
The script's -f/-r checks do not validate these record rules. They follow symlinks and describe current file/readability conditions, not ownership, format or future access. Inspect the complete supplied input separately. This is a bounded report for that contract, not a general CSV validator.
The owner report emits one owner per input record, sorted with the already taught command-scoped C locale. Duplicates stay in the report. The script neither groups owners nor counts distinct people. Empty valid input produces zero output bytes, not an invented blank record or an error message.
2. Preserve processing and output-write failures
The complete pipeline is built from taught parts:
cut -d ',' -f 3 -- "$1" | env LC_ALL=C sort
This is a script excerpt, not a prompt command with an already-defined $1.
cut selects the comma-delimited third field; -- ends its option parsing
and the quoted positional parameter supplies one path. The pipe connects
its stdout to sort's stdin. The external env command gives only the
launched sort the LC_ALL=C override. No parent locale, profile or system
configuration changes. Do not run env without its command.
Child-local pipefail and an if condition inspect the whole pipeline's status. If all stages, including the output-writing sort, succeed, exit 0 is justified. Otherwise the script diagnoses failure and exits 4. This does not mask a failed final write with an unconditional success afterward.
Unlike the previous captured count, this report streams data to stdout. A failed run can leave partial text in the caller's output file. Any nonzero run leaves an incomplete report, even if it contains plausible rows. Preserve it as failure evidence and do not accept it as a finished report. Our synthetic failure below happens to leave empty stdout; that does not promise that every future failure will do so.
Exercise: report owners and verify every row
Goal: produce the exact sorted owner report, distinguish valid empty input from rejected/missing input, and retain reliable processing status.
Starting state: use the ordinary nonzero-UID account in the full declared Ubuntu guest. The prior task is settled and a fresh task directory can be created. Every input and script is supplied below; no prior practice file is required as a hidden dependency.
Establish the known shell and owned directory
Run one line at a time and stop after unexpected setup/file errors. Inspect the taught origins first:
type cd pwd printf set declare type id ps mkdir ls cat wc cut sort env touch nano rm rmdir exit '[' bash
type -a ls
type -P ls
type -P bash
Require the expected Bash builtins and guest executables. Preserve only the understood color-only ls alias, with no hidden function or unknown origin. In particular, cut, env and sort must be the expected utilities, not custom child-inherited replacements.
id -u
id -un
ps -p $ -o comm=
ps -p 1 -o comm=
set -o
declare -p BASH_ENV
declare -p SHELLOPTS BASHOPTS
declare -p LC_ALL LC_COLLATE LANG
Require the recorded ordinary guest identity, Bash and systemd PID 1. Keep parent pipefail, errexit, allexport, nounset and posix off, as in the prior script task. Preserve a different setup rather than changing it. BASH_ENV must be absent; --noprofile/--norc do not suppress it. The existing option variables must be ordinary readonly declarations without export x. Record the named locale declarations or individual absence results for later comparison; do not change them or execute printed declarations. This script needs no new parent or script result variable.
Inspect the known parent and prospective task:
ls -ld ~/linux-practice
ls -ld ~/linux-practice/build-a-defensive-report-script
Require the ordinary owned parent and task name absent. Use the resume branch for an existing task. After acceptance:
mkdir ~/linux-practice/build-a-defensive-report-script
ls -ld ~/linux-practice/build-a-defensive-report-script
Accept the ordinary owned directory, then enter and verify separately:
cd ~/linux-practice/build-a-defensive-report-script
pwd
ls -a
Require the exact recorded task path and only dot entries before creating the two first inputs:
printf '%s\n' 'B01,done,Mira' 'B02,open,Asha' 'B03,done,Mira' 'B04,hold,Dev' 'B05,open,Asha' 'B06,done,Bo' > 'owner records.txt'
touch 'empty records.txt'
ls -ld -- 'owner records.txt' 'empty records.txt'
cat 'owner records.txt'
cat 'empty records.txt'
wc -l -- 'owner records.txt' 'empty records.txt'
Require ordinary owned single-link files. The first contains exactly the six supplied records and six newlines. The second must have zero bytes as well as zero newlines; the taught touch creates an empty file only because its name was confirmed absent. Preserve both inputs throughout.
Before running, manually extract the owner sequence in source order: Mira, Asha, Mira, Dev, Asha, Bo. Predict the full sorted output while keeping both occurrences of each repeated owner.
Save the complete owner script
Confirm owner-report.sh absent in the known inventory, then open it:
ls -a
After accepting only the known inputs and the absent script name:
nano owner-report.sh
Enter this complete script with a final newline. Save with the taught Ctrl+O, confirm the filename, then Ctrl+X; do not paste the Markdown fences:
#!/bin/bash
set -o pipefail
if [ "$#" -ne 1 ]; then
printf '%s\n' 'Usage: owner-report.sh INPUT' >&2
exit 2
fi
if [ ! -f "$1" ]; then
printf '%s\n' 'Input must be a regular file.' >&2
exit 3
fi
if [ ! -r "$1" ]; then
printf '%s\n' 'Input must be readable.' >&2
exit 3
fi
if cut -d ',' -f 3 -- "$1" | env LC_ALL=C sort; then
exit 0
else
printf '%s\n' 'Could not produce owner report.' >&2
exit 4
fi
Inspect the saved file before any run:
ls -ld -- owner-report.sh
cat owner-report.sh
ls -a
Require its exact complete contents and ordinary owned single-link identity
with read access. No chmod is needed for the explicit /bin/bash form.
The argument-count check comes before $1, followed by current path/read
checks. Statuses 2, 3 and 4 are this script's chosen contract, not universal
meanings. The input's field format remains a separate inspection obligation.
Run the valid report into fresh captures
Require owners.out and owners.err absent. Every caller redirection below
uses new named outputs separate from the source; > or 2> would truncate
an existing file. Recheck the exact cwd, owned script/input and absence
before each later run too.
/bin/bash --noprofile --norc owner-report.sh 'owner records.txt' > owners.out 2> owners.err
printf 'owner report exit: %s\n' "$?"
Record the immediate actual status before another command replaces it. Require 0 for a completed report, then inspect:
ls -ld -- owners.out owners.err
cat owners.out
cat owners.err
wc -l -- owners.out owners.err
Require ordinary owned single-link captures, zero-byte stderr and this exact six-line, six-newline stdout:
Asha
Asha
Bo
Dev
Mira
Mira
Match each occurrence to its source row. Sorting changes order, not the number of records. A six-line report of statuses or a deduplicated owner list would still violate this contract despite looking tidy.
Verify empty input, argument count and missing-path outcomes
Require empty.out and empty.err absent, and recheck the owned empty input's zero-byte size before:
/bin/bash --noprofile --norc owner-report.sh 'empty records.txt' > empty.out 2> empty.err
printf 'empty-input report exit: %s\n' "$?"
Require status 0 and both captures zero bytes. Inspect their identity, size and contents; zero newlines alone is insufficient to prove emptiness. No printf adds an artificial blank report row in this streaming design.
After confirming no-argument.out and no-argument.err absent:
/bin/bash --noprofile --norc owner-report.sh > no-argument.out 2> no-argument.err
printf 'no-argument report exit: %s\n' "$?"
Require 2, zero-byte stdout and exactly Usage: owner-report.sh INPUT plus
a newline on stderr. Inspect the actual captures before proceeding.
Require missing.txt, missing.out and missing.err absent; do not remove a real file to induce failure. After that inventory check:
/bin/bash --noprofile --norc owner-report.sh missing.txt > missing.out 2> missing.err
printf 'missing-input report exit: %s\n' "$?"
Require 3, zero-byte stdout and exactly Input must be a regular file. plus
a newline on stderr. A successful empty input and a missing input therefore
have different statuses and diagnostics despite both having no report rows.
Exercise processing failure without changing a live input
This separate supplied child fixture starts at the pipeline with a confirmed missing operand. It deliberately bypasses the normal validation checks. It neither claims those checks accepted the missing path nor simulates a real race or ordinary-user permission denial.
Confirm report-failure.sh, missing-after-check.txt, processing.out and processing.err absent in the known task inventory. After acceptance:
nano report-failure.sh
Enter, save and inspect this entire script and its ordinary owned single-link identity before execution:
#!/bin/bash
set -o pipefail
if cut -d ',' -f 3 -- 'missing-after-check.txt' | env LC_ALL=C sort; then
exit 0
else
printf '%s\n' 'Could not produce owner report.' >&2
exit 4
fi
After the explicit path/capture absence and script checks:
/bin/bash --noprofile --norc report-failure.sh > processing.out 2> processing.err
printf 'synthetic report-processing exit: %s\n' "$?"
Require 4. The stderr capture must retain cut's actual missing-operand
diagnostic and the script's Could not produce owner report. line.
This fixture's stdout is empty, but a nonzero result would make any
saved output incomplete, even if another failure left partial rows.
ls -ld -- processing.out processing.err
cat processing.out
cat processing.err
set -o
declare -p LC_ALL LC_COLLATE LANG
Require parent pipefail and all recorded named locale declarations/absence
states unchanged. The child and command-scoped settings did not become
parent configuration. Do not suppress a pipeline diagnostic or replace
its status with a successful later inspection command's $?.
Independent task: report the status field from a second dataset
Keep every guided input/result. Confirm 'status records.txt', status-report.sh, statuses.out, statuses.err, status-missing.out and status-missing.err absent. Create the complete second input only after the known directory/absence gates:
printf '%s\n' 'C01,open,Ivo' 'C02,done,Nia' 'C03,open,Ivo' 'C04,hold,Nia' > 'status records.txt'
ls -ld -- 'status records.txt'
cat 'status records.txt'
wc -l -- 'status records.txt'
Require the ordinary owned single-link file, all four exact three-field records and four newlines. The status field is already defined as field 2.
Create status-report.sh with this complete starter. It intentionally still selects the owner field, so adapt it before claiming a status report:
#!/bin/bash
set -o pipefail
if [ "$#" -ne 1 ]; then
printf '%s\n' 'Usage: status-report.sh INPUT' >&2
exit 2
fi
if [ ! -f "$1" ]; then
printf '%s\n' 'Input must be a regular file.' >&2
exit 3
fi
if [ ! -r "$1" ]; then
printf '%s\n' 'Input must be readable.' >&2
exit 3
fi
if cut -d ',' -f 3 -- "$1" | env LC_ALL=C sort; then
exit 0
else
printf '%s\n' 'Could not produce status report.' >&2
exit 4
fi
Before hints or the answer:
- Change only the selected field needed for the status report. Preserve the checks, quoted input, C-locale sort, duplicates and pipeline decision.
- Save and inspect every line and the script's owned identity. Predict the full sorted status sequence directly from the four source records.
- Actually run the adapted script on the spaced second input using fresh statuses.out/statuses.err. Record its immediate status and compare every output occurrence, the newline count and zero-byte stderr.
- Recheck missing.txt absent and actually run the adapted script using new status-missing.out/status-missing.err. Verify the same path-rejection contract. Recheck all three original inputs and the parent settings.
Success: exact owner and independent status reports preserve each record's selected value, valid empty input succeeds without a blank row, missing/count/processing cases are distinguished, and no failed output is accepted as a complete report. Explain the different protections from quoting, input predicates, format inspection and pipeline status.
Graduated hints
- Count positions from one: ID, status, owner. A successful pipeline can still select the wrong field.
- Keep one selected value for every source record, including repetitions. The taught sort does not require a deduplication option.
- Use the independent names and the existing explicit Bash/status pattern. Do not overwrite a guided capture or modify an input to force a result.
Check Your Understanding
- Why is a valid empty file different from a missing file, even when both attempts have zero report rows?
- Why can a report have the right number of lines and still be wrong? Which checks establish its field, order and repeated values?
- Why is exit 0 safe after this pipeline condition succeeds, and why must partial stdout from a nonzero run remain incomplete?
Answer and Reasoning
The adapted pipeline selects field 2; this is the changed excerpt inside status-report.sh:
if cut -d ',' -f 2 -- "$1" | env LC_ALL=C sort; then
After the saved-script, input, cwd and absent-capture checks:
/bin/bash --noprofile --norc status-report.sh 'status records.txt' > statuses.out 2> statuses.err
printf 'independent status-report exit: %s\n' "$?"
Require 0 before accepting the report. Inspect ordinary owned single-link captures, complete output and newline count:
ls -ld -- statuses.out statuses.err
cat statuses.out
cat statuses.err
wc -l -- statuses.out statuses.err
Stdout must contain exactly four newline-terminated lines:
done
hold
open
open
The repeated open values come from C01 and C03. Zero-byte stderr and the successful status support processing success, while this row comparison checks semantic correctness. A sorted owner report would not satisfy the independent request, even with four lines and status 0.
After reconfirming missing.txt and the new captures absent:
/bin/bash --noprofile --norc status-report.sh missing.txt > status-missing.out 2> status-missing.err
printf 'independent missing-input exit: %s\n' "$?"
Require 3 and inspect the resulting files:
ls -ld -- status-missing.out status-missing.err
cat status-missing.out
cat status-missing.err
cat 'owner records.txt' 'empty records.txt' 'status records.txt'
wc -l -- 'owner records.txt' 'empty records.txt' 'status records.txt'
set -o
declare -p LC_ALL LC_COLLATE LANG
Require zero-byte stdout, the exact regular-file rejection line/newline on stderr, unchanged six/zero/four-record inputs, parent pipefail off and unchanged named locale states. Read each original file as well as the counts.
Understanding-check feedback
- The empty file satisfies the owned input contract and processes zero records successfully. The absent path is rejected before processing, with status 3 and a diagnostic. Rows alone cannot distinguish them.
- The wrong field, wrong order or lost/replaced duplicates can produce a plausible count. Map every output occurrence to the defined source field, then compare the complete C-locale sorted sequence.
- The if condition includes all pipeline stages under pipefail, including the final output-writing sort. Only its success permits exit 0. Streaming data can precede a later error, so any nonzero outcome leaves the report incomplete regardless of how plausible its existing rows look.
Diagnose and finish without altering the inputs
Wrong fields require inspecting the saved selector and source contract; missing rows require comparing duplicates and complete source contents. Unexpected utility/write errors require their actual stderr and status. Do not add sudo, suppress errors, change locale globally or introduce a filter that silently removes records. This script does not diagnose or repair every malformed data file automatically.
After all tasks, recheck known parent/task identities and exact cwd:
ls -ld ~/linux-practice
ls -ld ~/linux-practice/build-a-defensive-report-script
Require ordinary owned directories before entering and checking:
cd ~/linux-practice/build-a-defensive-report-script
pwd
Require the recorded task path before inventorying the twenty named files:
ls -a
ls -ld -- owner-report.sh report-failure.sh status-report.sh 'owner records.txt' 'empty records.txt' 'status records.txt'
ls -ld -- owners.out owners.err empty.out empty.err no-argument.out no-argument.err missing.out missing.err
ls -ld -- processing.out processing.err statuses.out statuses.err status-missing.out status-missing.err
Require only these recognized ordinary owned single-link files and dot entries. Read any uncertain contents and preserve unexpected entries or unfinished evidence. Establish actual documented rm confirmation responses. Only after acceptance, remove the scripts and inputs:
rm -i -- owner-report.sh report-failure.sh status-report.sh 'owner records.txt' 'empty records.txt' 'status records.txt'
Each target has its own prompt. Declining one does not cancel later ones; if stopping, decline every remaining prompt and do not start another group. After accepting that group, remove the recognized captures:
rm -i -- owners.out owners.err empty.out empty.err no-argument.out no-argument.err missing.out missing.err
Proceed only after accepting the preceding group; apply the same refusal rule:
rm -i -- processing.out processing.err statuses.out statuses.err status-missing.out status-missing.err
Inspect remaining entries:
ls -a
Require the task empty before returning and checking:
cd ~/linux-practice
pwd
Require the recorded shared-root path and inspect the task entry:
ls -ld -- build-a-defensive-report-script
Only after accepting that ordinary owned empty directory:
rmdir -- build-a-defensive-report-script
Retain the shared root, parent settings and all unrelated data. The final
challenge supplies its own complete inputs and script; this lesson need
not leave hidden retained state for it. On resume, inspect saved script
versions and existing captures before a new run. Do not overwrite failure
evidence or replay a truncating redirection blindly. A missing old status
cannot be reconstructed from a later $?; an unexecuted branch remains
unverified. Partial cleanup removes only remaining recognized names after
their checks, without recreating deleted evidence.
Sources and other study views
- S18 — Bash 5.2: conditions, pipefail and script status
- S19 — GNU Coreutils: delimited fields, sorting, env and file checks
- S25 — Ubuntu Noble ps: selected guest/shell context
- S33 — Ubuntu Noble nano
- S67 — GNU nano 7.2: save and inspect the complete script
The Bash 5.2 and nano 7.2 sources match the selected families; packaging and configuration can differ. The current Coreutils manual is newer than the target 9.4 tools, so only the established bounded forms are used. The simple data contract and supplied failure fixture define what these checks establish; they do not validate arbitrary CSV or every permission/race case.
Revision rebuilds the report and failure model. Quick Reference retrieves the contract and selected run forms.