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.

Go Cli 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()
}