← blog · November 17, 2026

Writing a Script-Friendly CLI: Exit Codes, stdout vs stderr, JSON Output, TTY Detection and Signals

Why does a CLI that works perfectly by hand quietly produce wrong results inside a pipeline? Practical rules and Go examples for exit codes, stdout vs stderr, machine-readable output, terminal detection, signals and broken pipes.

A command line tool has two kinds of users: the person typing in a terminal, and the script, CI job or other program that calls it. Tools written with only the first user in mind tend to betray the second. They exit zero on failure, print progress bars into redirected output, corrupt JSON with color escapes and leave half-written files behind on Ctrl-C. The result is familiar: the tool works perfectly when you try it by hand and quietly produces wrong results the moment it lands in a pipeline. This post covers the contract that makes a CLI safe to automate, with Go examples for each piece.

The contract has four channels

A CLI talks to the outside world through its exit code, standard output, standard error and the signals it receives. If a script author can trust all four, your tool ends up in automation. If one of them is unreliable, people wrap it in workarounds and eventually replace it.

Exit codes are the only signal that matters

The shell, set -e, CI runners and process supervisors look at the exit code and nothing else. Nobody parses your error message. So the first rule is simple: every failure path exits non-zero.

A useful convention:

  • 0 for success.
  • 1 for a general failure: the operation was attempted and did not work.
  • 2 for usage errors such as an unknown flag or a missing argument. Go's standard flag package exits with 2 on parse errors, so this is an established convention.
  • 130 when interrupted with Ctrl-C. Shells report 128 plus the signal number, and SIGINT is 2.

If you want more meaning than that (a separate code for "nothing changed", say), document it and never change it. grep returns 1 for no match and 2 for an error, and scripts have relied on that distinction for decades.

The classic Go trap is os.Exit. It does not run deferred functions. If main defers closing a file, removing a temp directory or flushing a buffer, and some error path calls os.Exit(1), the cleanup never happens. log.Fatal does the same thing internally. The fix is to move all the work into a function that returns an error and exit in exactly one place:

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	context.AfterFunc(ctx, stop)
	err := run(ctx, os.Args[1:], os.Stdout, os.Stderr)
	interrupted := ctx.Err() != nil
	stop()
	os.Exit(exitCode(err, interrupted))
}

func exitCode(err error, interrupted bool) int {
	var uerr *usageError
	switch {
	case err == nil:
		return 0
	case errors.As(err, &uerr):
		return 2
	case interrupted:
		return 130
	default:
		return 1
	}
}

Every defer inside run now executes when run returns, and the exit comes afterwards. Note that the interruption is recorded before calling stop(): stop also cancels the context, so checking afterwards would make every error look like an interrupt. usageError is a small error type you define yourself. The second benefit is testability. You can call run with arguments and two buffers and assert on output and error directly, without spawning a subprocess.

stdout is for data, stderr is for humans

Only the data your tool produces goes to standard output. Progress, warnings, summaries like "processed 3 files" and error messages go to standard error. The reason is redirection. Someone running tool list > out.txt or tool list | jq wants only the data in the file or pipe, and still wants to see progress in the terminal. Mixing the two either corrupts the data or hides what is happening.

The robust way to enforce this is the pattern above: pass two separate io.Writer values into run. Writing to an injected writer instead of calling fmt.Println everywhere makes it hard to use the wrong stream, and lets tests capture each one separately.

One more detail: if you buffer stdout with bufio.Writer, call Flush before exiting and check the error it returns. A full disk or a closed pipe surfaces exactly there. Ignore it and the tool emits truncated output and exits zero.

Machine-readable output is a separate interface

An aligned table is pleasant to read, but when a script parses it with awk, every change in column width breaks something. Offer a second format: --json or --output json. Here is a firm opinion: do not pass off columnar plain text as "machine readable". Emit real JSON. JSON tolerates added fields without breaking old parsers, and values with spaces, newlines or Unicode stop being a problem.

JSON output is a contract too:

  • Keep field names and types stable. Renaming a header in the human table is fine; renaming a JSON field is a breaking change.
  • For long lists, consider one JSON object per line (JSON Lines). Consumers can stream it, and you do not have to hold the whole result in memory.
  • Never leave half a JSON document on stdout when something fails. Either write a valid document or write nothing; the error itself belongs on stderr and in the exit code.

Terminal or pipe?

Colors, progress bars, interactive confirmations and pagers only make sense when a human is watching. You find out by checking whether the stream is attached to a terminal. In Go, term.IsTerminal(int(os.Stdout.Fd())) from golang.org/x/term answers that.

Rules worth following:

  • Enable color only when the target stream is a terminal, and decide separately for stdout and stderr; with tool 2>errors.log, stdout may still be a terminal.
  • Disable color when the NO_COLOR environment variable is set to a non-empty value. It is a widely adopted convention. Also offer --color=always|never|auto so people who want color in CI logs can have it.
  • Before asking for confirmation, check that standard input is a terminal. If it is not, fail and require an explicit flag such as --yes. Otherwise the tool either waits for input forever in CI or treats empty input as consent.
  • Draw progress on stderr, and skip it entirely when stderr is not a terminal. A CI log full of carriage returns is unreadable.

Signals and half-finished work

Ctrl-C sends SIGINT; container runtimes and supervisors send SIGTERM when stopping a process. By default Go terminates immediately and no deferred calls run. The signal.NotifyContext call above turns those signals into context cancellation. Every long-running operation should take that context and return cleanly when it is cancelled: network calls via http.NewRequestWithContext, loops by checking ctx.Err() on each iteration.

The answer to half-written files is atomic writes. Write to a temporary file in the same directory as the target, call Sync, close it, and only if everything succeeded os.Rename it over the target. A rename within one filesystem either happens completely or not at all, so an interrupted run leaves the old file intact. Creating the temp file under os.TempDir breaks this when the target lives on a different filesystem, because the rename then fails; that is why the same directory matters.

Think about the second Ctrl-C as well. If cleanup is slow, the user presses it again. Once the stop function returned by NotifyContext has been called, the signal goes back to its default behavior. The context.AfterFunc(ctx, stop) line in the example (Go 1.21 and later) does that on the first signal: the first press starts a graceful shutdown, the second one kills the process. That is what users expect. Without it, a stuck cleanup step swallows Ctrl-C and kill -9 becomes the only way out.

Broken pipes

When you run tool list | head -n 5, head exits after five lines and your tool keeps writing to a closed pipe. If the program has not installed its own handler for SIGPIPE, the Go runtime terminates it with SIGPIPE on such a write to stdout or stderr. That is usually correct, and shells do not treat it as a failure. The problem appears in code that catches SIGPIPE with signal.Notify, or listens for all signals: now the write returns EPIPE, the tool reports it as an ordinary error and exits with 1, and scripts with set -o pipefail fail for no good reason. Do not catch SIGPIPE unless you have a deliberate reason; if you do, treat syscall.EPIPE as a quiet exit.

When not to bother

For a throwaway helper that only you will ever run, most of this discipline is overkill. Correct exit codes are still mandatory, because someone will eventually put it in a script. If your tool is fully interactive (a full-screen terminal UI), offering separate non-interactive subcommands is cleaner than bolting machine output onto the UI. And resist adding many output formats: human text plus JSON covers most tools, while YAML, CSV and templating each bring their own maintenance and testing cost.

Checklist

Before shipping, try these: tool bad-flag; echo $? should print 2. tool list > /dev/null should still show progress and warnings in the terminal. tool list --json | jq . should parse cleanly. tool list | head -n 1 should finish without printing an error. NO_COLOR=1 tool list should have no color. Ctrl-C in the middle of a long operation should leave the target file intact and exit with 130. A tool that passes these six checks will not make the scripts that depend on it quietly produce wrong results.