How-To Guide

How to Build a CLI Tool with Go and Cobra

Build a testable Go CLI with Cobra: subcommands, persistent and local flags, required options, context cancellation, shell completion, and error exit codes.

On this page

  1. Introduction
  2. Create a testable project layout
  3. Model subcommands and arguments
  4. Persistent flags and configuration
  5. Context, signals, and exit codes
  6. Shell completion
  7. Test the command tree
  8. Common pitfalls
  9. Conclusion

Introduction

Go’s standard library can parse flags, but a real CLI usually needs more: nested subcommands, global options, generated help, shell completion, and a clear exit code when something fails. Cobra is the most widely used library for that job in the Go ecosystem. It is the command layer behind tools such as kubectl, Hugo, and many internal operator CLIs.

Cobra is not a framework that hides Go. A command is a struct, a handler is a function, and flags are typed values. The hard part is structure: where commands are constructed, how errors travel to main, and how tests avoid global state. This tutorial builds a small task runner with a root command, a build subcommand, a persistent --verbose flag, required flags, context cancellation, and completion. The examples target Go 1.22 or newer.

Create a testable project layout

Start with a module and a layout that keeps main boring:

mkdir taskctl && cd taskctl
go mod init example.com/taskctl
go get github.com/spf13/cobra@latest
taskctl/
  main.go
  cmd/root.go
  cmd/build.go
  internal/build/build.go

main.go should do only three things: build the root command, execute it, and translate an error into an exit code:

package main

import (
    "fmt"
    "os"

    "example.com/taskctl/cmd"
)

func main() {
    if err := cmd.Execute(); err != nil {
        fmt.Fprintln(os.Stderr, "error:", err)
        os.Exit(1)
    }
}

The command constructor returns a fresh tree instead of mutating package-level variables. That single decision makes tests reliable, because flags and arguments from one test do not leak into the next:

package cmd

import (
    "context"

    "github.com/spf13/cobra"
)

func NewRootCmd() *cobra.Command {
    root := &cobra.Command{
        Use:           "taskctl",
        Short:         "Build and inspect tasks",
        SilenceUsage:  true,
        SilenceErrors: true,
    }

    root.PersistentFlags().Bool("verbose", false, "enable verbose logging")
    root.AddCommand(newBuildCmd())

    return root
}

func Execute() error {
    return NewRootCmd().ExecuteContext(context.Background())
}

SilenceUsage prevents Cobra from printing the full help text after a runtime failure. Usage belongs with parsing errors; a failed build should print the failure, not a wall of flags. SilenceErrors lets main decide how to format the error exactly once.

Model subcommands and arguments

A subcommand should validate its arguments before doing work. Cobra provides built-in validators such as cobra.ExactArgs, cobra.MaximumNArgs, and cobra.NoArgs:

package cmd

import (
    "fmt"

    "github.com/spf13/cobra"
)

func newBuildCmd() *cobra.Command {
    var output string
    var config string

    build := &cobra.Command{
        Use:   "build <input>",
        Short: "Build a task file",
        Args:  cobra.ExactArgs(1),
        RunE: func(cmd *cobra.Command, args []string) error {
            verbose, err := cmd.Flags().GetBool("verbose")
            if err != nil {
                return err
            }

            result, err := buildFile(args[0], output, config, verbose)
            if err != nil {
                return fmt.Errorf("build %s: %w", args[0], err)
            }

            fmt.Fprintln(cmd.OutOrStdout(), result)
            return nil
        },
    }

    build.Flags().StringVarP(&output, "output", "o", "dist", "output directory")
    build.Flags().StringVarP(&config, "config", "c", "", "configuration file")
    _ = build.MarkFlagRequired("config")

    return build
}

MarkFlagRequired returns an error because the flag name might be misspelled. Ignoring it with _ is common, but in a large command tree it is safer to handle the error during construction or assert it in a test. StringVarP binds the flag to a local variable; the action reads it directly instead of performing a type assertion on any.

Keep the actual build in a separate package:

func buildFile(input, output, config string, verbose bool) (string, error) {
    if input == "" {
        return "", errors.New("input is required")
    }
    // Validate paths, read the config, and perform the build here.
    return fmt.Sprintf("built %s into %s", input, output), nil
}

That separation lets you test path handling and build behavior without Cobra, and test command wiring without touching the filesystem.

Persistent flags and configuration

Persistent flags are inherited by subcommands. Use them for concerns that apply everywhere, such as --verbose, --config, or --timeout. Local flags belong to one command. Avoid defining a local flag with the same name as a persistent flag; the lookup order becomes confusing and help output can show two entries.

Bind global flags explicitly in each action with cmd.Flags().GetBool("verbose"); cmd.Flags() includes inherited persistent flags. If you prefer Viper for configuration files and environment variables, keep the precedence explicit and documented. A common order is: command-line flag, environment variable, config file, default. Viper can implement that order, but it also adds a global singleton, so pass values into your business logic rather than reading Viper deep inside it.

For environment fallbacks without Viper, read the environment while constructing the default:

defaultOutput := os.Getenv("TASKCTL_OUTPUT")
if defaultOutput == "" {
    defaultOutput = "dist"
}
build.Flags().StringVarP(&output, "output", "o", defaultOutput, "output directory")

Validate environment values with the same rules as flags. An invalid TASKCTL_TIMEOUT should produce a clear startup error, not a silent fallback that hides a misconfiguration.

Context, signals, and exit codes

Use ExecuteContext so a cancelled context reaches commands that perform I/O. For a CLI that should stop cleanly on Ctrl+C, derive the context from a signal-aware parent:

func Execute() error {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()
    return NewRootCmd().ExecuteContext(ctx)
}

Inside a long-running action, pass cmd.Context() to HTTP requests, database calls, and subprocesses. Check ctx.Err() between stages and return a wrapped error. Do not call os.Exit inside a RunE; it bypasses deferred cleanup and makes the command impossible to test. Let the error propagate to main.

Reserve exit code 0 for success and 1 for runtime failure. If you need to distinguish usage errors, inspect the error returned by Cobra or wrap validation failures in a sentinel type and map them in main. Document the codes; scripts depend on them more than humans do.

Shell completion

Recent Cobra versions add a completion command automatically. Generate scripts for the supported shells and tell users how to install them:

taskctl completion bash > /etc/bash_completion.d/taskctl
taskctl completion zsh > "${fpath[1]}/_taskctl"
taskctl completion fish > ~/.config/fish/completions/taskctl.fish

You can customize or disable the default command with root.CompletionOptions.DisableDefaultCmd = true. For dynamic arguments, set ValidArgsFunction on the command. It receives the current arguments and the word being completed, and returns candidates plus a directive:

build.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    if len(args) > 0 {
        return nil, cobra.ShellCompDirectiveNoFileComp
    }
    files, _ := filepath.Glob(toComplete + "*")
    return files, cobra.ShellCompDirectiveDefault
}

Completion functions must be fast and must not mutate state. They run in a separate process invoked by the shell, often on every Tab press. Avoid network calls and expensive filesystem walks.

Test the command tree

Cobra makes command-level tests straightforward when the tree is constructed per test:

func execute(t *testing.T, args ...string) (string, error) {
    t.Helper()
    root := NewRootCmd()
    var out bytes.Buffer
    root.SetOut(&out)
    root.SetErr(&out)
    root.SetArgs(args)
    err := root.Execute()
    return out.String(), err
}

func TestBuildRequiresConfig(t *testing.T) {
    _, err := execute(t, "build", "input.txt")
    if err == nil {
        t.Fatal("expected an error when --config is missing")
    }
}

Add tests for unknown commands, too many arguments, a successful build with a temporary directory, and cancellation. Assert on the error text only where it is part of the contract; assert on behavior and exit status otherwise. If a command writes files, use t.TempDir() and never the repository root.

Common pitfalls

  • Package-level command variables. They retain flags and arguments between tests.
  • Ignoring the error from Execute. The process exits 0 even when the command failed.
  • Calling os.Exit in a handler. Deferred cleanup and tests break.
  • Using SilenceUsage without printing the error. The user sees nothing.
  • Required flags on the wrong command. A persistent flag and a local flag with the same name are different flags.
  • Completion functions with side effects. They run in a short-lived process and should be pure.
  • Secrets in flags. Arguments are visible in process listings and shell history; use environment variables or stdin.

Conclusion

Cobra’s value is structure: a command tree, typed flags, generated help, and a completion command. The engineering discipline around it matters more than the library itself. Construct the tree in a function, return errors from RunE, execute with a context, keep business logic outside the command layer, and test the tree as a caller would. Those choices make a Go CLI predictable for users and maintainable for the next contributor.

Sources: Cobra documentation, Go context package, Go os/signal package.

FAQ

Should I use Run or RunE in Cobra?
Prefer RunE when the command can fail. It returns an error to Execute, which lets main choose the exit code and keeps the command testable. Run is fine only for commands that cannot fail.
How do I test a Cobra command without running the binary?
Build a fresh command tree in a constructor, set its output and argument slice with SetOut, SetErr, and SetArgs, then call Execute. A fresh tree per test avoids flag and state leakage between cases.
Why is my required flag not enforced?
MarkFlagRequired only affects parsing for that specific flag set. If the flag is defined on a parent as a persistent flag or on a different command, marking a local flag with the same name does not make the parent flag required. Check where the flag is registered.

Related Examples

Interactive Tools for This Topic