Stage 3 · Build
Building CLI Tools
Cobra Basics
Commands, flags, subcommands, and auto-completion for professional CLI tools.
Why Cobra
Cobra is the Go CLI framework used by kubectl, helm, docker, and Hugo. It provides command parsing, flag handling, help generation, and auto-completion out of the box. If you are building a CLI tool in Go, use Cobra.
go get github.com/spf13/cobra@latest
go install github.com/spf13/cobra-cli@latest
# Scaffold a new project
cobra-cli init mytool
cd mytool && go run .cobra-cli scaffolds a project with a root command and standard directory structure. The generated code is production-ready — just add your logic.
Root Command
The root command is the entrypoint of your CLI. It defines the program name, short description, and the base behavior when no subcommand is specified.
Subcommands
Subcommands group related functionality. Each subcommand is a cobra.Command added to the root or to another subcommand. This creates a natural hierarchy.
Flags and Arguments
Flags configure command behavior. Cobra supports persistent flags (inherited by subcommands) and local flags (specific to one command).
Binding flags to package-level variables makes them easy to override in tests. You can set the variables directly without going through the CLI parser.
Auto-Completion
Cobra generates shell completions for Bash, Zsh, Fish, and PowerShell. Users can enable completions with a single command.
# Generate shell completions
kube-guard completion bash > /etc/bash_completion.d/kube-guard
kube-guard completion zsh > ~/.zfunc/_kube-guard
kube-guard completion fish > ~/.config/fish/completions/kube-guard.fish
# Or install the completion command
kube-guard completion bash --installShell completions make your CLI discoverable. Users can type kube-guard scan <TAB> and see available namespaces. This dramatically improves the user experience for complex tools.
Help System
Cobra generates help text automatically. Every command gets --help for free. Customize the help template for your organization's style.
Use camelCase for flag names: --kubeconfig, --outputFormat. Use short flags for commonly used options: -o, -v, -f. Always provide --help for every command. These conventions match what users expect from established CLIs.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.