0Pricing
Go Academy · Lesson

Subcommands and Command Groups

Building multi-level CLI hierarchies

Hierarchical commands

Cobra supports arbitrary nesting: root → subcommand → sub-subcommand. Users call app resource action like kubectl get pods.

Adding subcommands

Build each subcommand as a separate cobra.Command and register it with its parent:

var userCmd = &cobra.Command{Use: "user", Short: "Manage users"}
var userCreateCmd = &cobra.Command{Use: "create", Short: "Create user", RunE: createUser}
func init() {
    userCmd.AddCommand(userCreateCmd)
    rootCmd.AddCommand(userCmd)
}

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