Building a CLI that respects your terminal
Most CLIs are bad citizens. Let's talk about color, pagers, and exit codes.
Most command-line tools treat your terminal like a dumping ground. Wall of unstyled text. No pager. Exit code 0 even when things fail. Colors that break when you pipe to a file.
We can do better.
The basics
A well-behaved CLI should:
- Detect whether stdout is a TTY and adjust output accordingly
- Use
NO_COLORandFORCE_COLORenvironment variables - Pipe long output through a pager
- Return meaningful exit codes
- Write errors to stderr, data to stdout
# your tool should handle all of these gracefully
mytool list
mytool list | grep something
mytool list > output.txt
mytool list 2>/dev/null
None of this is hard. It just requires giving a damn.