Skip to content

Building production CLIs in Go with Cobra

Use Cobra to scaffold a multi-command Go CLI with flags, subcommands, shell completion, and config-file loading via Viper. Covers exit codes, logging, and testing.

Almost every well-known Go CLI — kubectl, helm, docker, hugo, gh, terraform — is built with Cobra (or its predecessor). Cobra handles the part of a CLI you do not want to write yourself: subcommand routing, flag parsing, shell completion, help-text generation, version output. This article shows the Cobra layout Stack Harbor uses for production CLIs delivered to clients.

How to verify

After scaffolding, a real CLI takes shape immediately:

go install github.com/spf13/cobra-cli@latest
cobra-cli init --pkg-name example.com/mycli
go run . --help
go run . version
go run . completion bash > /etc/bash_completion.d/mycli

cobra-cli init writes cmd/root.go and main.go. cobra-cli add <name> adds a subcommand. Shell completion is built-in — call <cli> completion <bash|zsh|fish> and source the output.

What’s happening

Cobra is a parser-plus-command-tree. The root command is a *cobra.Command with subcommands attached via AddCommand. Each command has its own RunE function, its own flag set, and its own help text. When the user types mycli sub --flag val arg, Cobra walks the tree to find sub, parses flags into the bound destinations, and calls RunE.

Flag binding is two-step: declare the flag on the command, optionally bind it to a Viper key. Viper merges env vars, config files, defaults, and CLI flags into a single source of truth (covered in golang-viper-config-management). The pairing of Cobra (UX) + Viper (config plumbing) is the standard pattern.

Cobra emits machine-readable shell completion scripts for bash, zsh, fish, and powershell. The completion logic knows your subcommands and flag names — users get tab completion out of the box.

The procedure

  1. Initialize a CLI module.

    mkdir mycli && cd mycli
    go mod init example.com/mycli
    go install github.com/spf13/cobra-cli@latest
    cobra-cli init --pkg-name example.com/mycli

    That creates main.go (calls cmd.Execute) and cmd/root.go (defines the root command).

  2. Add subcommands.

    cobra-cli add version
    cobra-cli add migrate
    cobra-cli add migrate -p migrateCmd up

    Each add writes a new file under cmd/. The -p parentCmd flag attaches a nested subcommand.

  3. Author a subcommand with flags and validation. cmd/migrate.go:

    package cmd
    
    import (
        "context"
        "errors"
    
        "github.com/spf13/cobra"
    )
    
    var migrateCmd = &cobra.Command{
        Use:   "migrate",
        Short: "Run database migrations",
        Long:  "Apply or revert SQL migrations against the configured database.",
        Args:  cobra.NoArgs,
        RunE: func(cmd *cobra.Command, args []string) error {
            ctx := cmd.Context()
            dir, _ := cmd.Flags().GetString("dir")
            if dir == "" {
                return errors.New("--dir is required")
            }
            return runMigrate(ctx, dir)
        },
    }
    
    func init() {
        rootCmd.AddCommand(migrateCmd)
        migrateCmd.Flags().StringP("dir", "d", "migrations", "Migration directory")
    }

    RunE (returns error) is preferred over Run because the error becomes the process exit code.

  4. Wire context for cancellation. Make the CLI respect Ctrl+C by binding a context to the root command:

    // cmd/root.go
    import (
        "context"
        "os/signal"
        "syscall"
        "github.com/spf13/cobra"
    )
    
    func Execute() {
        ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
        defer stop()
        rootCmd.SetContext(ctx)
        if err := rootCmd.Execute(); err != nil {
            os.Exit(1)
        }
    }

    Subcommands call cmd.Context() and pass it to anything I/O-bound.

  5. Version subcommand from build-time injection.

    // cmd/version.go
    var (
        version = "dev"
        commit  = "none"
        date    = "unknown"
    )
    
    var versionCmd = &cobra.Command{
        Use:   "version",
        Short: "Print version",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Printf("%s commit=%s date=%s\n", version, commit, date)
        },
    }

    Inject at build time:

    go build -ldflags="-X example.com/mycli/cmd.version=1.0.0 -X example.com/mycli/cmd.commit=$(git rev-parse HEAD) -X example.com/mycli/cmd.date=$(date -u +%FT%TZ)"

    GoReleaser does this automatically — see golang-goreleaser-binary-release.

  6. Ship shell completions. Add a completion subcommand:

    var completionCmd = &cobra.Command{
        Use:   "completion [bash|zsh|fish|powershell]",
        Short: "Generate completion script",
        ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
        Args:  cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
        RunE: func(cmd *cobra.Command, args []string) error {
            switch args[0] {
            case "bash":
                return rootCmd.GenBashCompletion(os.Stdout)
            case "zsh":
                return rootCmd.GenZshCompletion(os.Stdout)
            case "fish":
                return rootCmd.GenFishCompletion(os.Stdout, true)
            case "powershell":
                return rootCmd.GenPowerShellCompletion(os.Stdout)
            }
            return nil
        },
    }
  7. Test subcommands. Cobra commands are normal Go — test them by buffering output and asserting:

    func TestVersion(t *testing.T) {
        buf := &bytes.Buffer{}
        rootCmd.SetOut(buf)
        rootCmd.SetArgs([]string{"version"})
        if err := rootCmd.Execute(); err != nil {
            t.Fatal(err)
        }
        if !strings.Contains(buf.String(), "commit=") {
            t.Fatal("missing commit info")
        }
    }

Common pitfalls

  • Run swallows errors silently. Use RunE so the error returns to the caller and Cobra prints it. Otherwise a failed command exits 0.
  • Flags declared at package init may collide between subcommands. Use cmd.Flags() (subcommand-local) instead of rootCmd.PersistentFlags() unless the flag truly applies to every subcommand.
  • Global state via var defeats testing. Pass dependencies as function arguments or capture them in a closure on the command’s RunE.
  • cobra.NoArgs is opinionated. Use cobra.MinimumNArgs(1) / MaximumNArgs(N) / ExactArgs(N) so misuse produces a helpful error instead of silently ignoring.
  • Help text bleeds when not formatted. Keep Short under 50 chars; put detail in Long (rendered on --help).

Stack Harbor delivers Cobra-based operator CLIs alongside the services we run for clients — single-binary tools for migrations, backups, and on-call diagnostics that ship as part of the operating model. See how that fits into our managed operations practice.