Go CLI Tool with Cobra

Build a command-line tool in Go using Cobra with subcommands, persistent flags, shell completion, help templates, and configuration loading from environment.

GoCli Tooling

Code

snippet
package main

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

var rootCmd = &cobra.Command{Use: "mycli", Short: "A Go CLI tool"}

var buildCmd = &cobra.Command{
  Use:   "build [input]",
  Short: "Build project",
  Run: func(cmd *cobra.Command, args []string) {
    output, _ := cmd.Flags().GetString("output")
    fmt.Printf("Building %s → %s\n", args[0], output)
  },
}

func main() {
  buildCmd.Flags().StringP("output", "o", "dist", "Output directory")
  rootCmd.AddCommand(buildCmd)
  rootCmd.Execute()
}

How the snippet works

The snippet is organized around the function main.

What to watch for

  • Dependency check: github.com/spf13/cobra — not built-in, must be present in the project.

Applying it

The demo output is labeled (Building), so each line traces straight back to the statement that printed it.

Statements that decide the outcome

func main() {
buildCmd.Flags().StringP("output", "o", "dist", "Output directory")
rootCmd.AddCommand(buildCmd)
rootCmd.Execute()
}

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `github.com/spf13/cobra`. Without it the snippet will not load.