CLI ToolsApr 13, 2026·3 min read

Cobra — Modern CLI Framework for Go Applications

Cobra is the most popular Go library for building command-line applications. It powers the CLI of Kubernetes (kubectl), GitHub CLI, Docker, Hugo, and hundreds of other tools — providing subcommands, flags, auto-generated help, and shell completions.

Agent ready

Safe staging for this asset

This asset is staged first. The copied prompt tells the agent to inspect the staged files and ask before activating scripts, MCP config, or global config.

Stage only · 17/100Policy: stage
Agent surface
Any MCP/CLI agent
Kind
CLI Tool
Install
Stage only
Trust
Trust: Established
Entrypoint
step-1.md
Safe staging command
npx -y tokrepo@latest install 0ffadd25-373d-11f1-9bc6-00163e2b0d79 --target codex

Stages files first; activation requires review of the staged README and plan.

TL;DR
Cobra is the Go CLI framework powering kubectl, GitHub CLI, and Docker with subcommands, flags, help generation, and completions.
§01

What it is

Cobra is a Go library for building command-line applications with subcommands, flags, auto-generated help text, and shell completions. It is the most widely used CLI framework in the Go ecosystem, powering the CLIs of Kubernetes (kubectl), GitHub CLI (gh), Docker, Hugo, and hundreds of other tools.

Cobra targets Go developers building CLI tools that need structured subcommands (like git commit, docker run, or kubectl apply). It handles argument parsing, validation, help generation, and man page creation.

§02

How it saves time or tokens

Cobra eliminates the boilerplate of parsing flags, validating arguments, and generating help text. Its code generator scaffolds new commands with a single command. You focus on business logic while Cobra handles the CLI framework concerns.

Shell completion scripts (bash, zsh, fish, PowerShell) are auto-generated from your command definitions. Without Cobra, writing and maintaining completion scripts is a manual, error-prone process.

§03

How to use

  1. Install Cobra and initialize a project:
go install github.com/spf13/cobra-cli@latest
cobra-cli init myapp
cd myapp
  1. Add a subcommand:
cobra-cli add serve
cobra-cli add migrate
  1. Implement the command logic in cmd/serve.go:
var serveCmd = &cobra.Command{
    Use:   "serve",
    Short: "Start the HTTP server",
    Run: func(cmd *cobra.Command, args []string) {
        port, _ := cmd.Flags().GetInt("port")
        fmt.Printf("Starting server on port %d\n", port)
    },
}

func init() {
    serveCmd.Flags().IntP("port", "p", 8080, "Port to listen on")
    rootCmd.AddCommand(serveCmd)
}
§04

Example

A complete CLI with persistent flags and nested subcommands:

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

var verbose bool

var rootCmd = &cobra.Command{
    Use:   "myapp",
    Short: "My application CLI",
}

var deployCmd = &cobra.Command{
    Use:   "deploy [environment]",
    Short: "Deploy to an environment",
    Args:  cobra.ExactArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("Deploying to %s (verbose=%v)\n", args[0], verbose)
    },
}

func main() {
    rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
    rootCmd.AddCommand(deployCmd)
    rootCmd.Execute()
}
§05

Related on TokRepo

§06

Common pitfalls

  • Putting all command logic in the Run function. Extract business logic into separate packages and keep commands thin. This makes the logic testable independently of the CLI framework.
  • Overusing persistent flags. Persistent flags propagate to all subcommands. If a flag only applies to one command, make it a local flag to keep help text clean.
  • Forgetting to call cobra.CheckErr() on errors. Cobra provides consistent error handling. Use it instead of log.Fatal() to get proper exit codes and error formatting.

Frequently Asked Questions

What major projects use Cobra?+

Cobra powers the CLIs of Kubernetes (kubectl), GitHub CLI (gh), Docker, Hugo, Helm, Terraform, and many other popular Go projects. It is the de facto standard for Go CLI development.

How does Cobra compare to urfave/cli?+

Both are popular Go CLI frameworks. Cobra is more opinionated with its code generator and file structure. urfave/cli is more lightweight and uses a functional style. Cobra has better shell completion support and is more widely adopted in large projects.

Can Cobra generate man pages and documentation?+

Yes. Cobra can auto-generate man pages, markdown documentation, and shell completion scripts from your command definitions. Run 'cobra-cli docs' or use the doc generation package programmatically.

Does Cobra work with Viper for configuration?+

Yes. Cobra and Viper (also by spf13) are designed to work together. Viper handles configuration files (YAML, JSON, TOML, env vars) and Cobra handles CLI flags. You can bind Cobra flags to Viper configuration keys for a unified config approach.

How do I add shell completion to a Cobra application?+

Cobra generates shell completion scripts automatically. Add a 'completion' command to your root command with 'rootCmd.AddCommand(completionCmd)'. Users then run 'myapp completion bash > /etc/bash_completion.d/myapp' to install completions.

Citations (3)

Discussion

Sign in to join the discussion.
No comments yet. Be the first to share your thoughts.

Related Assets