返回资讯中心
外部精选
软件工程
#开发者实时流

CLI Style

An elegant interface for a more automated age. A numbered style guide for the command line, written for whoever reads it: the person who types a command, or the program that runs one.

Hacker News 最新imagetic2026/10/14 · 2026/10/1430 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

An elegant interface for a more automated age. A numbered style guide for the command line, written for whoever reads it: the person who types a command, or the program that runs one.

The command line is more popular today than at any point in its history. Every wave of computing that was supposed to replace it—the graphical desktop, the web, cloud infrastructure, and now AI—ended up multiplying its reach instead. It didn't just survive each shift; it grew through every one of them, because plain text is still the only interface that composes, scripts, and leaves a legible trail.

Yet as its reach expanded, the craft of designing for it remained mostly oral tradition. Graphical platforms have had Human Interface Guidelines for forty years; the terminal had scattered man pages and tribal knowledge. Think of this document as the Human Interface Guidelines for the command line—and, because we now live in a world where software invokes software on our behalf, the Agent Interface Guidelines as well.

You do not need two interfaces. The qualities that make a CLI intuitive for a person—a consistent sentence grammar, typed streams, predictable exit codes, and self-documenting commands—are the exact qualities that make it reliable for an agent. What agents change is the cost of ambiguity: a person can muddle through a surprise prompt or a status line on stdout, while an automated caller will hit that trap at machine speed.

Frameworks like spf13/cobra, spf13/viper, and spf13/pflag were built with these principles in mind and provide much of this out of the box, but nothing here is specific to Go or the spf13 tooling. These fifty-six principles apply to any command-line application in any language.

Principles are numbered and grouped into ten parts with permanent anchors (like #preview-is-a-diff) so you can cite them in design reviews and pull requests. All examples use a fictional application named app.

Four guidelines read differently for Human and Agent — color, progress, terminal detection, and prompts. Those carry a marked aside, and they are where most otherwise-good applications break today. The other fifty-two need no split: the right answer is the same for both readers, and they are stated plainly.

An accompanying SKILL.md is published at spf13/cli-style—install it into your coding agent so it builds and audits CLIs against this guide automatically.

Subject, object, verb, target, modifier. app noun verb target --modifier. A command line is a sentence in an imperative language; make it parse like one. What can be said aloud can be guessed, and what can be guessed can be composed by a script that never read your manual.

Hierarchy carries meaning that flags can't. If you're reaching for a mode flag, what you wanted was a subcommand. The tree is a map that can be explored a level at a time, and the path is the address: no hidden mode silently changes what the same words mean.

A subtree owns its flags. If two options can't coexist, design the grammar so they cannot be combined in the first place: split conflicting actions into separate subcommands, and collapse mutually exclusive choices into a single valued flag. Where shorthand flags like --quiet and --verbose must coexist on the same command, define a clear precedence (for example, --verbose overrides --quiet, or last flag wins) rather than failing with a flag-conflict error.

Short, lowercase, no punctuation, easy to say. The name will be typed thousands of times and spoken in hallways. Check that it isn't already taken by something on a normal system: shadowing an existing command is a bug you inflict on everyone.

Reuse the same verb across every noun. If list works on clusters, it works on users, keys, and regions too. Eight verbs applied to twenty nouns is a smaller thing to learn than forty bespoke commands, and it teaches itself: anyone who has mastered half your application has already mastered the rest.

Pass the target of the command as a positional argument and every other option as a named flag. Never put an optional positional argument before a required one, and never change what a positional argument means based on the one before it. If a reader has to count positions to know what 3 or true means, it should have been a flag.

Everything after it is data, even if it starts with a dash. Filenames, search patterns, and arguments forwarded to a wrapped program all depend on it. Free to support, expensive to omit.

The common path takes no flags. Every flag a user must pass is a decision you declined to make for them. Make the default right and the first attempt is usually the correct one.

Consistent inside your application, and consistent with everyone else's. A novel spelling of a common idea is a tax you charge every person who types it and every agent that tries to guess it.

Long flags are what get written into scripts, documentation, and issue comments, because they explain themselves. Short flags are a convenience for the handful of options typed daily, and a permanent allocation from a very small namespace. Spend them carefully.

Published, stable, inspectable. Anyone can ask the application where a value came from and get a straight answer: the layer that won, named, instead of bisecting their dotfiles.

How long a value should live tells you where it belongs. That's the whole decision, and it's almost always obvious once asked.

Use the operating system's standard directories on Linux, macOS, and Windows, and honor XDG_CONFIG_HOME, XDG_CACHE_HOME, and XDG_STATE_HOME when set. Don't scatter dotfiles across the home directory, don't invent a new location, and keep cache separate from configuration so clearing one never destroys the other.

A fresh install on an empty machine must do something useful. Configuration files are an optimization for repeat users, never a prerequisite. An application that can't start without a config file can't be tried, by anyone or by anything.

Read stdin when no input file is given. Write to stdout rather than to a file chosen on the user's behalf. An application that composes is worth several that don't; composition is how your readers build things you never anticipated.

--preview beats --dry-run. --force describes your internals; --overwrite describes what happens to someone's files. Name the flag after the thing the user cares about, which is never your implementation. When the name states the effect, reading it is knowing it: no translation step, for any reader.

--preview is easier to type and clearer than --dry-run; --fresh beats --no-cache-write. Single-word commands and flags force you to find the real word for the concept, and they eliminate separator and casing ambiguity — nobody has to guess whether you spelled it --no-cache, --nocache, or --NoCache.

Show the delta you would produce; don't narrate the steps you might take. "Would create 3 resources" is a log line. The resources themselves are an answer: a person can review it like a patch, a pipeline can evaluate it, before anything is applied.

Re-running a command either reaches the same state safely or fails cleanly and changes nothing. Half-applied is the one unacceptable outcome. Retries are how everything recovers: a dropped connection, a Ctrl-C, a flaky agent. Making them safe makes the whole failure model simple.

Scale friction to the cost of recovery, not the size of the command. Undoable changes should run immediately with zero prompts. Recoverable changes (restarting a service, rotating a key) proceed by default and support --preview. Unrecoverable deletions confirm once (y/N at a terminal, --yes in automation). Catastrophic actions—or bulk operations with destructive blast radius if mis-scoped—print what will be destroyed and require naming the target itself (interactively or via --confirm <target>), never a blanket --yes.

A command called status does not refresh a cache, rotate a token, or send telemetry. Hidden side effects are how an application loses the trust it needs to be given credentials and let loose, by a person or by a program with far more authority than attention.

Nobody should have to remember what you named things. Complete subcommands, flags, and live resource names at the prompt, and list valid choices whenever an option takes a fixed set. What can be discovered can be used; what must be recalled from memory will be mistyped or hallucinated.

Generate help text, completions, man pages, and machine schema from one source — the command tree itself — so they cannot drift. Documentation that ships inside the binary can't go stale relative to the binary, and what's installed is always what's described.

A flag table explains what is legal; examples show what is idiomatic. Include three concrete invocations someone can copy and run—the common path, a preview or modifier path, and a piped or scripted path. For both people and agents, three working commands teach the grammar faster than fifty lines of flag descriptions.

Running the bare application prints help rather than an error. Support app help as a subcommand alongside -h (terse, fits on a screen) and --help (complete) at every level. Help that was asked for is a success and exits zero; help printed because someone got the command wrong is a failure and exits two.

The version subcommand prints what a bug report needs: version, commit, and platform. Pair app version --json with app help --json so a script or agent that has never seen your application before can inspect its build and full command tree in one call.

One line: the documentation URL and how to report a bug. It costs a line and saves a search.

stdout is data. stderr is everything else: logs, progress, warnings, prompts. No exceptions, no "just this one status line." Typed streams are what let a person pipe the output somewhere and still watch what the application is doing, and let a parser read stdout without stripping the chatter out first. Telemetry never corrupts the payload.

Terse by default, --verbose to expand. Verbosity is a request, never a default. Every line printed is spent from someone's finite budget — attention on a screen, context in a window — and a wall of successful output is exactly what hides the one line that mattered.

--json on every command that returns data, including errors. Generate it from the same values as the human rendering rather than assembling it separately: two code paths become two behaviors, and the machine path is the one nobody notices breaking.

Print what was produced, or print nothing. "Successfully completed operation" tells no one anything the exit code didn't. Silence is a valid and often correct response to a job well done.

Anything conveyed by color must also be carried by a word or a symbol. Color is a courtesy one reader can accept, and gibberish to everything else.

A person watching a terminal absorbs a red error faster than the word "error." Take the gift.

A pipe, a log aggregator, and a screen reader all strip or mangle the codes. If the color carried the meaning, the meaning is gone.

So decorate, never encode. Turn it off when stdout isn't a terminal, when NO_COLOR is set, and when --no-color is passed.

Spinners and bars are for a human watching. Without a TTY, print nothing, or one line per meaningful milestone.

A live progress bar is reassurance: the application is working, here is how far along it is.

A progress bar redrawn into a log file produces megabytes of escape codes and no information. Without eyes, motion is just noise.

Silence on a slow operation looks identical to a hung process or a blocked stdin read. Never leave the caller guessing whether the application is working or wedged: when an operation waits on the network, a lock, or a remote state transition, emit what you are doing on stderr and update it as phases change. Pair status updates with --timeout so automated callers can bound the wait.

Zero results is a legitimate answer, not an error, and exits zero. On a terminal, say what

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →