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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does this need from the package registry?
- These are real dependencies: `github.com/spf13/cobra`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.