Keeping Command Output Machine-Readable

A command used in a pipeline should keep its data stream in the declared format, with unrelated progress and diagnostics directed separately.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a parser expectation
  2. Check terminal and redirected runs
  3. Run the command with a downstream parser as a test
  4. Define behavior on failure as part of the output contract

Trace a parser expectation

A CSV consumer expects a header and rows. A progress line inserted before the header may be interpreted as malformed data. See CSV field order.

Check terminal and redirected runs

Some commands change output when a terminal is present. Machine-readable behavior should be specifically requested or documented where it matters. Capturing output can verify both streams and exit status.[1]

Run the command with a downstream parser as a test

A command emitting one JSON object is used by a report importer. A greeting sent to standard output would precede the object and break a parser expecting exactly one value. Send progress and diagnostics through their documented channel. See capturing command output.

stdout expected: {"count":3} followed by an allowed newline
stderr may show progress or diagnostics
Consumer can parse stdout alone

Define behavior on failure as part of the output contract

Decide whether there is no data, a structured error, or partial results with a nonzero status. Test with stdout redirected through a validator and confirm exit status separately.

References

  1. The Open Group, POSIX Shell Command Language ↩