How to Build a CLI Tool with Go and Cobra
Introduction
Cobra is the most popular CLI framework for Go. It provides subcommands, flags, help generation, and shell completion out of the box.
Step 1: Install Cobra
go get github.com/spf13/cobra
Step 2: Define Commands
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 the project",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
output, _ := cmd.Flags().GetString("output")
fmt.Printf("Building %s → %s\n", args[0], output)
},
}
func init() {
buildCmd.Flags().StringP("output", "o", "dist", "Output directory")
rootCmd.AddCommand(buildCmd)
}
func main() {
rootCmd.Execute()
}
Step 3: Add Completion
rootCmd.AddCommand(&cobra.Command{
Use: "completion [shell]",
Short: "Generate shell completion",
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
rootCmd.GenBashCompletion(os.Stdout)
case "zsh":
rootCmd.GenZshCompletion(os.Stdout)
}
},
})
Conclusion
Cobra provides a declarative API for building professional CLI tools in Go. The built-in help, completion, and flag parsing save significant development time.