Exit Status and Command Output
Programs can report a successful run separately from whatever they write to an output stream. Callers use the exit status to decide whether to continue.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Recognize independent observations
A command can produce an empty file list because it searched an empty directory successfully. It can also produce no records because opening the directory failed. On common command-line systems, exit status zero indicates success and documented nonzero statuses convey other outcomes. Diagnostics may go to a separate stream. These observations all belong to the program's input and output.
Preserve an upstream failure
Imagine a job that exports a CSV and then archives the result. An archive can be created from a partial export, so the presence of an archive does not establish the export succeeded. Check the export process result before publishing the artifact. A function contract serves the same purpose within one program.[1]
Give a valid empty result its own interpretation
Consider a command that reads a list of building rooms and prints rooms with a reservation today. A valid file with no reservations can produce empty standard output and a success status. A missing file can also produce no rooms, yet its nonzero status and diagnostic identify why the query did not run. This distinction is important when a script creates a daily report from the result. Treating both forms of empty output as a successful query could publish a blank report after an input failure.
Write the three observations for each test case: the exit status, the data on standard output, and the diagnostic on standard error. A successful nonempty example verifies the output syntax, while a successful empty example verifies the zero-record contract. A failed read should verify both error reporting and the absence of a completed output. See standard output and standard error.
Observe work completed before a failure
A producer in a pipeline may write several valid records before failing. A reader receiving them can finish successfully even though it did not receive the complete input. The reported pipeline status depends on the shell's rules and settings. Test the actual arrangement using a synthetic producer that fails after one record. Pipeline exit status explains why the last command's status alone can be insufficient.
For file generation, a complete output can be published after checking the producer's outcome. Replacing a file after a complete write is one practical way to keep the previous complete file available during generation.