Why Your Go CLI Should Exit 2 on Bad Flags, Not 1
A script that calls your tool can only see one number. If you return 1 both for "the server said no" and for "you typed -timeuot", the caller cannot tell a runtime failure from a bug in its own command line. Exit 1 should mean the tool ran and failed; exit 2 should mean it was invoked wrongly.
Go's standard library already does half of this for you, which is why it is easy to break by accident.
What the flag package does by default
With flag.Parse on the default command line, the error mode is ExitOnError. A bad flag prints a message plus usage to stderr and exits with status 2. So the default is already right.
The trouble starts when you stop using the default. People move to a FlagSet with ContinueOnError so they can test the parser, then write this:
if err := fs.Parse(args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
Now a typo and a network failure are indistinguishable. Nothing crashes, nothing warns you, and the contract has quietly changed.
Why the split matters to callers
Plenty of established tools already use the distinction. grep exits 0 for a match, 1 for no match, and 2 for an error. diff uses 1 for "files differ" and 2 for trouble. In both, 1 is a normal answer, and 2 says "do not trust the output".
Even for a tool where 1 is just "failed", the split gives callers choices:
- Retry on 1 when the failure might be transient (timeout, 503).
- Never retry on 2, because the same wrong arguments will fail the same way.
- Page a human on 2 in a cron job, because someone edited a command line and broke it.
That retry rule alone is worth the effort. A wrapper that retries a malformed invocation five times with backoff is a small, stupid, avoidable waste.
A shape that keeps both codes honest
Put all the logic in a run function that takes its arguments and writers, and returns the exit code. main becomes one line.
package main
import (
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"time"
)
func run(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("fetch", flag.ContinueOnError)
fs.SetOutput(stderr)
timeout := fs.Duration("timeout", 5*time.Second, "request timeout")
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2 // the FlagSet has already printed the problem
}
if fs.NArg() != 1 {
fmt.Fprintln(stderr, "fetch: want exactly one URL")
fs.Usage()
return 2
}
client := &http.Client{Timeout: *timeout}
resp, err := client.Get(fs.Arg(0))
if err != nil {
fmt.Fprintln(stderr, "fetch:", err)
return 1
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintln(stderr, "fetch: unexpected status", resp.Status)
return 1
}
if _, err := io.Copy(stdout, resp.Body); err != nil {
fmt.Fprintln(stderr, "fetch:", err)
return 1
}
return 0
}
func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
Two details are easy to miss. First, -h makes Parse return flag.ErrHelp, and asking for help is not a mistake, so it returns 0 (the default ExitOnError mode does the same since Go 1.15). Second, the deferred Body.Close runs because run returns normally; only main calls os.Exit.
Quick detour: the missing positional argument
The flag package only validates flags. It has no opinion on whether you gave it the right number of arguments, so fs.NArg() is yours to check. That is the check people forget, and it is why "no arguments" often ends in a nil dereference or a confusing "unsupported protocol scheme" error with exit 1.
It is also a usage error in the same sense as a bad flag. Same exit code, same usage text.
Test the codes, not just the text
Because run takes writers, the contract fits in a table test with no subprocesses:
func TestExitCodes(t *testing.T) {
tests := []struct {
name string
args []string
want int
}{
{"unknown flag", []string{"-timeuot", "1s", "http://x"}, 2},
{"no url", nil, 2},
{"bad duration", []string{"-timeout", "soon", "http://x"}, 2},
{"help", []string{"-h"}, 0},
{"unreachable", []string{"-timeout", "100ms", "http://127.0.0.1:1"}, 1},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var out, errOut bytes.Buffer
if got := run(tc.args, &out, &errOut); got != tc.want {
t.Errorf("exit %d, want %d (stderr: %s)", got, tc.want, errOut.String())
}
})
}
}
The "bad duration" case is worth keeping. A malformed value for a typed flag is a parse error too, so it lands on 2 without extra code. The last case needs nothing listening on port 1, which is true on almost every machine but not a guarantee.
Checking it from the shell
$ fetch -bogus; echo $?
flag provided but not defined: -bogus
Usage of fetch:
-timeout duration
request timeout (default 5s)
2
If you ever see 1 there, something in your wiring has overridden the default. Also remember that a pipe hides the code: fetch -bogus | tee log reports tee's status unless you set pipefail.
What about 64?
BSD's sysexits.h defines EX_USAGE as 64, and some tools use it. It is a perfectly respectable choice, but Go's own flag package uses 2, shells use 2 for builtin misuse, and so does grep. Matching the standard library means your tool behaves the same whether the error came from your code or from the parser. I would take the consistency.
Whichever you pick, document it in your usage text or README in one line: 0 success, 1 runtime failure, 2 usage error. Callers will thank you, probably silently, which is the best a CLI author can hope for.