Go Academy · Lesson

Cobra Fundamentals

Root command, Run, Args, and help generation

Lesson 1 of 413 steps

Cobra Fundamentals is a free Go Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Cobra Fundamentals” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Cobra Fundamentals”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

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