CLI best practices
Context
Section titled “Context”Well‑designed CLI tools follow common conventions: help text, exit codes, output formatting, and error handling.
Best practices
Section titled “Best practices”- Help text – Provide
-hor--helpwith clear usage. - Exit codes –
0for success, non‑zero for errors. - Output – Use
fmt.Printlnfor normal output,fmt.Fprintln(os.Stderr, ...)for errors. - Silence – Allow quiet mode (
-q). - Progress – Use progress bars for long operations (e.g.,
github.com/schollz/progressbar). - Colour – Use colour for readability, but respect
NO_COLORenvironment variable. - Subcommands – Group related actions (like
git add,git commit). - Configuration – Support flags, environment variables, and config files (use Viper).
Example
Section titled “Example”A well‑structured CLI with proper exit codes.
Code example
Section titled “Code example”package main
import ( "flag" "fmt" "os")
func main() { name := flag.String("name", "", "your name") flag.Parse() if *name == "" { fmt.Fprintln(os.Stderr, "error: --name is required") os.Exit(1) } fmt.Printf("Hello, %s\n", *name) os.Exit(0)}Output (missing flag)
Section titled “Output (missing flag)”error: --name is required