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
-
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/mycliThat creates
main.go(callscmd.Execute) andcmd/root.go(defines the root command). -
Add subcommands.
cobra-cli add version cobra-cli add migrate cobra-cli add migrate -p migrateCmd upEach
addwrites a new file undercmd/. The-p parentCmdflag attaches a nested subcommand. -
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(returnserror) is preferred overRunbecause the error becomes the process exit code. -
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. -
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.
-
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 }, } -
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
Runswallows errors silently. UseRunEso 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 ofrootCmd.PersistentFlags()unless the flag truly applies to every subcommand. - Global state via
vardefeats testing. Pass dependencies as function arguments or capture them in a closure on the command’s RunE. cobra.NoArgsis opinionated. Usecobra.MinimumNArgs(1)/MaximumNArgs(N)/ExactArgs(N)so misuse produces a helpful error instead of silently ignoring.- Help text bleeds when not formatted. Keep
Shortunder 50 chars; put detail inLong(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.