0Pricing
Go Academy · Lesson

Cobra Fundamentals

Root command, Run, Args, and help generation

Cobra Fundamentals is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is Cobra?

Cobra is the most popular Go library for building CLI applications. It provides commands, flags, subcommands, help generation, shell completion, and argument validation.

Installing Cobra

Add cobra as a dependency and optionally use the CLI generator:

go get github.com/spf13/cobra
// Optional: cobra-cli for scaffolding
go install github.com/spf13/cobra-cli@latest
cobra-cli init myapp

Root command

Every Cobra app has a root command. Define it with Use, Short description, and a Run function:

var rootCmd = &cobra.Command{
    Use:   "myapp",
    Short: "My awesome CLI",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("Hello from root!")
    },
}
func main() { rootCmd.Execute() }

cobra.Command struct

Key fields: Use (command name + synopsis), Short (one-line description), Long (detailed help), Run (executes command), RunE (returns error).

RunE for error propagation

Use RunE instead of Run to return errors. Cobra prints the error and exits with a non-zero code automatically.

var rootCmd = &cobra.Command{
    RunE: func(cmd *cobra.Command, args []string) error {
        return doWork()
    },
}

Adding subcommands

Create subcommands as separate cobra.Command values and add them to the root with AddCommand:

var serveCmd = &cobra.Command{
    Use:   "serve",
    Short: "Start the server",
    RunE:  runServe,
}
func init() { rootCmd.AddCommand(serveCmd) }

Cobra project structure

Conventional layout: cmd/ directory with one file per subcommand, plus root.go. main.go only calls cmd.Execute().

cmd/
  root.go    // rootCmd definition
  serve.go   // serveCmd
  migrate.go // migrateCmd
main.go

Args validation

Use built-in validators like cobra.ExactArgs, MinimumNArgs, or a custom ValidArgsFunction:

var cmd = &cobra.Command{
    Args: cobra.ExactArgs(2),
    RunE: func(cmd *cobra.Command, args []string) error {
        fmt.Println(args[0], args[1])
        return nil
    },
}

Auto-generated help

Cobra generates --help / -h for every command and a help subcommand automatically. The text comes from Use, Short, Long, and flags.

Shell completion

Cobra generates completion scripts for bash, zsh, fish, and PowerShell out of the box via rootCmd.GenBashCompletion or the built-in completion subcommand.

Viper integration

Combine Cobra with Viper for configuration management: flags defined with Cobra bind to Viper keys so values can come from flags, env vars, or config files.

Quick Check

What is the difference between cobra.Command.Run and RunE?

Recap: Cobra Fundamentals

Key points:

  • cobra.Command with Use/Short/RunE is the core building block
  • rootCmd.AddCommand(subCmd) for hierarchical commands
  • cobra.ExactArgs/MinimumNArgs for argument validation
  • Help and completion generated automatically

Frequently asked questions

Is the “Cobra Fundamentals” lesson free?

Yes — the full text of “Cobra Fundamentals” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Cobra Fundamentals”?

Root command, Run, Args, and help generation You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Cobra Fundamentals” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Cobra Fundamentals
  2. Flags and Persistent Flags
  3. Subcommands and Command Groups
  4. Distributing CLI Tools
← Back to Go Academy