Parse Flags, Env Vars, and Exit Codes in a Go CLI
Build testable Go CLIs using flag.NewFlagSet, os.Getenv defaults, os.Stderr error messages, and clean integer exit codes. After this, scripts and containers can compose your tools reliably.
Skip ahead
Already separating main() from run(args []string) int? Jump to Case 2: env defaults with flag overrides or Case 4: testing CLI output in memory with bytes.Buffer.
In Linux, Docker, and CI pipelines, exit codes and stdout/stderr streams are the contract between your Go binary and everything orchestrating it. Calling os.Exit(1) (or log.Fatal) deep inside helper functions breaks two things at once: every pending defer cleanup is skipped immediately, and calling that helper from go test kills the entire test process.
Meanwhile, printing errors to os.Stdout instead of os.Stderr breaks shell pipelines like mycli export | jq . because downstream tools try to parse your error sentence as JSON. Verified on Go 1.27.
Case 1: Why returning int from run() beats calling os.Exit in helpers
When main() is just os.Exit(run(os.Args[1:])), every defer inside run() (closing temp files, flushing logs, shutting down servers) executes cleanly before the process exits:
package main
import "fmt"
func run() int {
defer fmt.Println("cleanup ran!")
return 1
}
func main() {
code := run()
fmt.Println("would exit with:", code)
}
cleanup ran!
would exit with: 1
Case 2: flag.NewFlagSet with os.Getenv fallback and flag override
Avoid global flag.String + flag.Parse() inside testable code—global flags register into a process-wide singleton (`flag.CommandLine`) and call os.Exit(2) on invalid input. Using flag.NewFlagSet with os.Getenv("PORT") as the default gives you container env defaults, CLI flag overrides, and repeatable unit tests:
package main
import (
"flag"
"fmt"
"os"
)
func run(args []string) int {
fs := flag.NewFlagSet("portcheck", flag.ContinueOnError)
port := fs.String("port", os.Getenv("PORT"), "listen port")
if err := fs.Parse(args); err != nil {
return 2
}
if *port == "" {
fmt.Fprintln(os.Stderr, "error: -port or PORT is required")
return 1
}
fmt.Printf("listening on :%s\n", *port)
return 0
}
func main() {
fmt.Println("missing:", run(nil))
os.Setenv("PORT", "9090")
fmt.Println("from_env:", run(nil))
fmt.Println("from_flag:", run([]string{"-port", "8080"}))
}
$ go run .
error: -port or PORT is required
missing: 1
listening on :9090
from_env: 0
listening on :8080
from_flag: 0
Case 3: Exit code and stream conventions expected by scripts and Docker
| Code / Stream | Meaning | Use for |
|---|---|---|
Exit 0 |
Success | Command completed cleanly |
Exit 1 |
Runtime or config failure | Missing required env/flag, failed HTTP/DB check |
Exit 2 |
Invalid CLI flag usage | Unknown flag or non-integer flag value |
os.Stderr |
Diagnostics and errors | Keeps os.Stdout strictly for machine-readable output |
Case 4: Unit testing CLI output without spawning subprocesses
Pass stdout, stderr io.Writer into run(args []string, stdout, stderr io.Writer) int and call fs.SetOutput(stderr). In go test, pass two bytes.Buffer instances—now your tests assert exact exit codes, stdout payloads, and stderr error messages in under a millisecond.
💡 Tip
After fs.Parse(args), any remaining positional arguments (like file paths) live in fs.Args(), and their count is fs.NArg().
Common mistakes
- Calling
log.Fatalinside helper functions: Callsos.Exit(1)immediately, skipping every deferred cleanup. - Printing errors with
fmt.Println: Writes toos.Stdoutand breaks shell pipes; always write errors toos.Stderr. - Placing flags after positional arguments: Standard
flagstops scanning flags at the first non-flag arg, somycli report.csv -port 8080ignores-port.
⚠ Warning
Never print secrets read from os.Getenv (API keys, database passwords) in startup logs or flag usage defaults. Log only non-sensitive settings like port and environment name.
What happens if you skip this
CLIs that exit inside helpers or mix errors into stdout skip file cleanups, break automated shell scripts and Docker healthchecks, and become painful to unit-test.
Related course: Go for Beginners.
About
Build testable Go CLIs using flag.NewFlagSet, os.Getenv defaults, os.Stderr error messages, and clean integer exit codes. After this, scripts and containers can compose your tools reliably.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.