How to Build a CLI in Go with Cobra
Table of Contents
Updated November 2026: Updated for Go 1.27 and Cobra v1.10.2: commands now use RunE and return errors, and I added persistent flags, shell completion and the cobra-cli generator.
Cobra
(github.com/spf13/cobra) is the most popular Go module for building command-line applications (CLIs). In this post, I build stringer, a small CLI that reverses and inspects strings. It is just big enough to cover the parts of Cobra you need every day: commands, aliases, argument validation, local and persistent flags, error handling with RunE, shell completion, and a version you set at build time.

https://github.com/spf13/cobra
Everything below is tested with Go 1.27 and Cobra v1.10.2.
What is Cobra
Cobra was created by Steve Francia (spf13 ), and a lot of the CLIs you use every day are built with it:
hugo- the static site generatorgh- the GitHub CLIkubectl- the Kubernetes CLI
What you get out of the box:
- Nested commands: a tree of commands with a single root, as deep and as wide as you need
- POSIX-style flags (via pflag ): bound to one command or inherited by all subcommands
- Generated help:
--helpand ahelpcommand for every command, customizable if you need it - Shell completion: a
completioncommand for Bash, Zsh, fish and PowerShell
Create the project
Bootstrap the module and add Cobra as a dependency:
mkdir stringer && cd stringer
go mod init github.com/ThorstenHans/stringer
mkdir -p cmd internal/stringer
touch main.go cmd/root.go internal/stringer/stringer.go
go get github.com/spf13/cobra@latest
The layout follows the convention Cobra’s own generator uses: one file per command in cmd/, the actual logic in a separate package, and a tiny main.go:
.
├── go.mod
├── main.go
├── cmd
│ └── root.go
└── internal
└── stringer
└── stringer.go
The root command
A Cobra command is a cobra.Command struct. Commands form a tree with a single root command, which is the entry point of the CLI. Add this to cmd/root.go:
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var (
version = "0.0.1"
verbose bool
)
var rootCmd = &cobra.Command{
Use: "stringer",
Version: version,
Short: "stringer - a simple CLI to transform and inspect strings",
Long: `stringer is a super fancy CLI (kidding)
Use stringer to modify or inspect strings straight from the terminal.`,
SilenceUsage: true,
}
func init() {
rootCmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "print what stringer is doing to stderr")
}
// Execute runs the command tree and returns the first error.
func Execute() error {
return rootCmd.Execute()
}
func debugf(cmd *cobra.Command, format string, a ...any) {
if verbose {
fmt.Fprintf(cmd.ErrOrStderr(), format+"\n", a...)
}
}
A few things worth pointing out:
- The root command has no
Runfunction. When users callstringerwithout a subcommand, Cobra prints the help. - Setting
Versiongives you a--version(and-v) flag for free. More on that at the end. --verboseis a persistent flag: it is defined on the root command and inherited by every subcommand. Flags added withFlags()instead are local to one command.SilenceUsage: truestops Cobra from dumping the full usage text whenever a command returns an error. A failing command should print the error, not a wall of help.
main.go calls Execute and turns an error into a non-zero exit code. Cobra has already printed the error (as Error: ... on stderr), so there is nothing left to print here:
package main
import (
"os"
"github.com/ThorstenHans/stringer/cmd"
)
func main() {
if err := cmd.Execute(); err != nil {
os.Exit(1)
}
}
Run go run . --help and you already get help for your first Cobra CLI, including the built-in completion and help commands.
Add the business logic
The logic itself doesn’t matter for this post. Put two small functions into internal/stringer/stringer.go:
package stringer
import (
"slices"
"unicode"
"unicode/utf8"
)
// Reverse returns input with its characters in reverse order.
func Reverse(input string) string {
r := []rune(input)
slices.Reverse(r)
return string(r)
}
// Inspect counts the characters of input, or only its digits.
func Inspect(input string, digits bool) (count int, kind string) {
if !digits {
return utf8.RuneCountInString(input), "char"
}
for _, c := range input {
if unicode.IsDigit(c) {
count++
}
}
return count, "digit"
}
Working on runes instead of bytes keeps both functions correct for input like héllo.
Add subcommands
I put every command into its own file. Create cmd/reverse.go:
package cmd
import (
"fmt"
"github.com/ThorstenHans/stringer/internal/stringer"
"github.com/spf13/cobra"
)
var reverseCmd = &cobra.Command{
Use: "reverse <text>",
Aliases: []string{"rev"},
Short: "Reverses a string",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
debugf(cmd, "reversing %q", args[0])
_, err := fmt.Fprintln(cmd.OutOrStdout(), stringer.Reverse(args[0]))
return err
},
}
func init() {
rootCmd.AddCommand(reverseCmd)
}
The init function registers reverseCmd as a subcommand of rootCmd. Besides that:
Aliaseslets users call the command asstringer revas well.Args: cobra.ExactArgs(1)validates the positional arguments before your code runs. Cobra also shipsNoArgs,MinimumNArgs,MaximumNArgs,RangeArgs,OnlyValidArgsandMatchAllto combine them.RunEinstead ofRun: the function returns anerror, and Cobra hands it back toExecute. I useRunEfor every command that does real work, so errors flow up tomaininstead of ending inos.Exitcalls scattered over the codebase.- Writing to
cmd.OutOrStdout()instead ofos.Stdoutmakes the command testable: in a test, callrootCmd.SetOut(&buf)androotCmd.SetArgs(...)and assert on the buffer.
Add a local flag and return errors
Now cmd/inspect.go. It gets a local --digits flag (with the shorthand -d) and returns an error for empty input:
package cmd
import (
"errors"
"fmt"
"strings"
"github.com/ThorstenHans/stringer/internal/stringer"
"github.com/spf13/cobra"
)
var onlyDigits bool
var inspectCmd = &cobra.Command{
Use: "inspect <text>",
Aliases: []string{"insp"},
Short: "Inspects a string",
Args: cobra.ExactArgs(1),
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(cmd *cobra.Command, args []string) error {
input := args[0]
if strings.TrimSpace(input) == "" {
return errors.New("text must not be empty")
}
debugf(cmd, "inspecting %q (digits only: %t)", input, onlyDigits)
count, kind := stringer.Inspect(input, onlyDigits)
if count != 1 {
kind += "s"
}
_, err := fmt.Fprintf(cmd.OutOrStdout(), "'%s' has %d %s\n", input, count, kind)
return err
},
}
func init() {
inspectCmd.Flags().BoolVarP(&onlyDigits, "digits", "d", false, "count only digits")
rootCmd.AddCommand(inspectCmd)
}
Flags().BoolVarP binds the flag to onlyDigits; the P suffix variants take a shorthand. There are the same helpers for strings, ints, durations, slices and more. If a flag is mandatory, call MarkFlagRequired("name"), and Cobra rejects the call before RunE runs. ValidArgsFunction: cobra.NoFileCompletions tells shell completion not to suggest file names for the argument, since inspect expects arbitrary text.
Time to try it:
go run . reverse foo
oof
go run . rev héllo
olléh
go run . inspect lorem
'lorem' has 5 chars
go run . insp A1B2C3 -d
'A1B2C3' has 3 digits
# the persistent flag works on every subcommand
go run . --verbose rev bar
reversing "bar"
rab
# errors from Args and RunE end up on stderr, exit code 1
go run . inspect " "
Error: text must not be empty
go run . reverse
Error: accepts 1 arg(s), received 0
And the generated help shows the alias, the local flag and the inherited global flag:
go run . inspect --help
Inspects a string
Usage:
stringer inspect <text> [flags]
Aliases:
inspect, insp
Flags:
-d, --digits count only digits
-h, --help help for inspect
Global Flags:
--verbose print what stringer is doing to stderr
Shell completion
Cobra adds a completion command to every CLI. It generates completion scripts for Bash, Zsh, fish and PowerShell, which complete subcommands, aliases and flags (including their descriptions):
go build -o ./dist/stringer .
# try it in the current zsh session
source <(./dist/stringer completion zsh)
# instructions for installing it permanently
./dist/stringer completion zsh --help
If you don’t want the command, set rootCmd.CompletionOptions.DisableDefaultCmd = true. For dynamic values (resource names fetched from an API, for example), set ValidArgsFunction on the command or call RegisterFlagCompletionFunc for a flag.
Set the version at build time
Remember the version variable in cmd/root.go? Because it is a package-level variable, you can override it at build time with -ldflags, which is how you stamp a release version or Git tag into the binary:
go run . --version
stringer version 0.0.1
go build -o ./dist/stringer \
-ldflags="-X 'github.com/ThorstenHans/stringer/cmd.version=0.0.2'" .
./dist/stringer --version
stringer version 0.0.2
Scaffold commands with cobra-cli
Writing the boilerplate by hand is fine for a handful of commands. For bigger CLIs, the Cobra generator
scaffolds the same cmd/ layout for you:
go install github.com/spf13/cobra-cli@latest
cobra-cli init # main.go, cmd/root.go and a LICENSE file
cobra-cli add reverse # cmd/reverse.go, registered on rootCmd
cobra-cli lives in its own repository and hasn’t had a release since v1.3.0 in 2022, but it still works with current Go and Cobra. I usually run it once to get started and write commands by hand afterwards. cobra-cli init --viper also wires up Viper
for config files and environment variables. I’d only add Viper when the CLI really needs a config file; for flags alone, Cobra is enough.
Recap
Go and Cobra are still my go-to combination for CLIs: subcommands, flags, help and shell completion come for free, and go build produces a single static binary that you can cross-compile for every platform. That is a big advantage over Node.js-based CLIs, which need a runtime on the user’s machine. If you prefer Rust, I covered the same idea in How to Build CLIs in Rust with StructOpt
. For a Go CLI that talks to a cloud service, look at azb in Azure Blob Storage using the Azure SDK for Go
.
You can find the source code of stringer on GitHub at github.com/ThorstenHans/stringer
.