Building Command Line Tools with Go

Go produces a single static binary, which makes it one of the best languages for command line tools: the result runs on a machine with no runtime installed, starts in milliseconds, and distributes as one file. The tooling story is unusually good too - the standard library covers flag parsing, and cobra gives you a command tree, help text, and shell completion almost for free. This page goes from a single binary to a well-behaved tool with subcommands, configuration, and a clean shutdown.

1. The Standard Library Is Enough for Small Tools

flag handles the common case: named flags, a usage message, and parsing from the command line.

package main

import (
    "flag"
    "fmt"
    "os"
)

func main() {
    var (
        verbose bool
        count   int
        name    string
    )

    flag.BoolVar(&verbose, "v", false, "enable verbose output")
    flag.IntVar(&count, "n", 1, "how many times to repeat")
    flag.StringVar(&name, "name", "world", "who to greet")
    flag.Parse()

    if flag.NArg() == 0 {
        fmt.Fprintln(os.Stderr, "expected at least one argument")
        flag.Usage()
        os.Exit(2)
    }

    for i := 0; i < count; i++ {
        if verbose {
            fmt.Fprintf(os.Stderr, "greeting %d of %d\n", i+1, count)
        }
        fmt.Printf("Hello, %s!\n", name)
    }
}

Two details matter for a real tool. The standard flag package stops parsing at the first non-flag argument, so tool -v sub --other will not see --other; if that trips you up, use flag.ContinueOnError with your own FlagSet, or move to cobra. And the exit code is part of your contract: 0 for success, 2 for a usage error, and a distinct non-zero code for each real failure.

2. A Command Tree with cobra

Once a tool has more than one mode, the flat flag list stops being readable. cobra turns a program into a tree of commands, each with its own flags, and generates the help and completion for you.

package main

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
    Use:   "ledger",
    Short: "A small double-entry ledger",
    SilenceUsage: true,
}

var versionCmd = &cobra.Command{
    Use:   "version",
    Short: "Print the version",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Fprintln(cmd.OutOrStdout(), "ledger 1.4.0")
    },
}

func init() {
    rootCmd.AddCommand(versionCmd)
    rootCmd.PersistentFlags().String("currency", "USD", "default currency")
}

func main() {
    if err := rootCmd.Execute(); err != nil {
        os.Exit(1)
    }
}

Two habits pay off immediately:

  • Set SilenceUsage: true on the root command. By default cobra prints the whole usage block after any error, which is noise for a runtime failure - the user wants the error, not a reminder of the flags.
  • Write to cmd.OutOrStdout() instead of fmt.Println. Then the command can be tested by swapping the output writer, and it can be embedded in another program.

A subcommand with its own flags looks like this:

var addCmd = &cobra.Command{
    Use:   "add <account> <amount>",
    Short: "Add a transaction to an account",
    Args:  cobra.ExactArgs(2),
    RunE: func(cmd *cobra.Command, args []string) error {
        amount, err := strconv.ParseFloat(args[1], 64)
        if err != nil {
            return fmt.Errorf("invalid amount %q: %w", args[1], err)
        }
        return ledger.Add(args[0], amount)
    },
}

Args: cobra.ExactArgs(2) turns a missing argument into a clear message instead of an index-out-of-range panic.

3. Configuration Comes from Three Places

A well-behaved tool merges configuration from, in increasing order of precedence: built-in defaults, a configuration file, environment variables, and command line flags.

type Config struct {
    Endpoint string
    Timeout  time.Duration
    Verbose  bool
}

func Load() (Config, error) {
    cfg := Config{
        Endpoint: "https://api.example.com",
        Timeout:  30 * time.Second,
    }

    if err := viper.SetConfigFile("ledger.yaml"); err == nil {
        if err := viper.ReadInConfig(); err != nil {
            var notFound viper.ConfigFileNotFoundError
            if !errors.As(err, &notFound) {
                return Config{}, fmt.Errorf("read config: %w", err)
            }
        }
    }

    viper.SetEnvPrefix("LEDGER")
    viper.AutomaticEnv()

    if err := viper.Unmarshal(&cfg); err != nil {
        return Config{}, fmt.Errorf("decode config: %w", err)
    }
    return cfg, nil
}

The rule is that flags win, because the user typed them last. Viper’s BindPFlag gives you that for free.

4. Signals and Graceful Shutdown

A command line tool that is killed mid-write can leave a file corrupted. Trap SIGINT and SIGTERM, stop accepting new work, finish what is in flight, and only then exit.

func run() error {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    srv := &http.Server{Addr: ":8080", Handler: handler()}

    errCh := make(chan error, 1)
    go func() {
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
            errCh <- err
        }
    }()

    select {
    case err := <-errCh:
        return err
    case <-ctx.Done():
        log.Println("shutting down")

        shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
        defer cancel()
        return srv.Shutdown(shutdownCtx)
    }
}

The same pattern applies to any long-running work: give it a context.Context, cancel it when the signal arrives, and wait for the goroutines to finish.

5. Output That Is Usable in a Pipeline

A tool that prints to stdout can be composed with other tools, so keep data on stdout and messages on stderr.

cmd.Println("processed 42 records")   // stdout: the result
cmd.PrintErrln("warning: 3 records skipped") // stderr: the commentary

Offer machine-readable output as well. A --format json flag that emits a JSON document makes the tool scriptable, and it costs little once the domain logic already returns structured data rather than printing as it goes.

type output struct {
    Processed int      `json:"processed"`
    Skipped   int      `json:"skipped"`
    Items     []Item   `json:"items"`
}

6. What to Take Away

  • Start with flag; move to cobra when the tool has subcommands.
  • Turn usage errors into exit code 2 and runtime errors into a distinct non-zero code.
  • Write output through the command object so the tool stays testable.
  • Merge defaults, file, environment, and flags in that order, with flags winning.
  • Trap the termination signals, drain the work, and exit cleanly.
  • Keep data on stdout and commentary on stderr.

Practice

GoCLIcobraConfigurationGraceful Shutdown

Approach: The question asks how to make a long-running command line tool behave properly under interruption, so reason from what the operating system actually does when it sends SIGINT or SIGTERM: the default disposition kills the process immediately, and whatever the process was writing at that moment is left half-written.

Steps:

  1. The default handler for SIGINT and SIGTERM terminates the process at once, without unwinding the stack and without running deferred functions - so a file being written is left incomplete.
  2. signal.NotifyContext installs a handler that cancels a context.Context instead of killing the process, which means the process now decides when to stop.
  3. The tool must then stop accepting new work, wait for the in-flight work to finish, and only then exit. http.Server.Shutdown with a timeout does exactly this for an HTTP server; for other work, pass the same context into the goroutines and wait on a sync.WaitGroup.
  4. The timeout matters: if a dependency hangs, the shutdown must still complete, so the context given to Shutdown should have a deadline (a common value is 10 to 15 seconds) and the process should exit with a non-zero status if the deadline passes.
  5. The exit status has to reflect what happened - a clean shutdown exits 0, a shutdown that timed out exits non-zero so a supervisor can notice - and any partially written output must be handled by the same graceful path, for instance by writing to a temporary file and renaming it once the work is complete.

Answer: Install a signal handler that cancels a context instead of killing the process, stop accepting new work when the context is cancelled, wait for the in-flight work to finish within a bounded timeout, flush and rename any output atomically, and exit 0 only if the drain completed - otherwise exit non-zero to signal that the shutdown was incomplete.

Found an issue with this content?

Tell us what could be improved.