Skip to content

Lesson 3 of 9 · 23m

stdout, stderr, Exit Codes, and Terminal Behavior

Separate data from diagnostics, choose meaningful exit statuses, handle pipes and TTYs correctly, and avoid output that breaks scripts.

The fastest way to make users hate a CLI is to print progress into the data stream. It works in a demo, then somebody runs tool list | jq and spends an hour discovering that Downloading index... is not valid JSON. Terminal behavior is not decoration. It is the difference between a tool and a trap.

stdout is the result; stderr is the story

Use stdout only for the requested output: table, JSON, file contents, or the final artifact path. Logs, progress bars, warnings, prompts, deprecation notices, and errors belong on stderr:

use std::io::{self, Write};

fn emit_result(json: &str, warning: &str) -> io::Result<()> {
    writeln!(io::stdout(), "{json}")?;
    writeln!(io::stderr(), "warning: {warning}")?;
    Ok(())
}

That separation is what lets callers compose your tool in pipelines without brittle scraping.

Exit codes are part of the contract

Zero means the requested operation succeeded. Nonzero means it did not. Reserve specific nonzero codes only if you intend to keep them stable:

0   success
1   general operational failure
2   invalid invocation or usage
3   input not found
4   permission or authorization failure
5   network or upstream service failure

Do not invent a different code for every possible error. Users need broad decisions — retry, fix input, reauthenticate, escalate — not a bingo card.

Pipes close, terminals disappear, and output is partial

When downstream exits early, writes can fail with EPIPE. A Unix filter such as head closing the pipe should not produce a panic:

if let Err(err) = writeln!(out, "{line}") {
    if err.kind() == io::ErrorKind::BrokenPipe {
        std::process::exit(0);
    }
    return Err(err.into());
}

Whether broken pipe is success depends on semantics. For streaming display output, success is usually correct. For a file transfer, it is absolutely not.

Detect TTYs, but expose explicit controls

Progress bars, colors, hyperlinks, and interactive prompts are for terminals. CI systems, cron, file redirection, and pipes are not terminals. Use crates such as anstream and anstyle, honor NO_COLOR, and provide explicit flags:

--color auto|always|never
--output json|table|plain
--no-progress

Auto-detection is a convenience, not a control. Scripts need deterministic behavior even when someone allocates a pseudo-TTY in CI.

Atomic output beats clever output

If your tool writes files, write to a temporary sibling path and rename it. If it prints structured output, either validate the whole document or stream in a documented format such as newline-delimited JSON. Half a JSON document followed by an error is not an interface.

Field notes

  • Never print secrets while explaining that a secret is invalid.
  • tracing and log output still need a destination policy; library defaults can leak into user-visible streams.
  • Prompts on non-interactive stdin should fail cleanly unless an explicit --yes or equivalent flag was supplied.
  • Progress bars must erase themselves correctly when stderr is redirected or the terminal is narrow.
  • If output can be consumed by machines, version its schema independently of the CLI release number.

Was this lesson helpful?

Sign in to rate