How do I build nested subcommands using cobra in Go?

Cobra is a powerful library for creating CLI applications in Go. One of its features is the ability to create nested subcommands, allowing for a more organized and hierarchical command structure. Below is an example of how to build nested subcommands using Cobra.

package main import ( "fmt" "github.com/spf13/cobra" "os" ) func main() { var rootCmd = &cobra.Command{ Use: "app", Short: "A root command", } var subCmd1 = &cobra.Command{ Use: "sub1", Short: "First subcommand", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Executing sub1 command") }, } var subCmd1_1 = &cobra.Command{ Use: "sub1_1", Short: "First nested subcommand", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Executing sub1_1 command") }, } var subCmd2 = &cobra.Command{ Use: "sub2", Short: "Second subcommand", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Executing sub2 command") }, } // Nesting the commands rootCmd.AddCommand(subCmd1) subCmd1.AddCommand(subCmd1_1) rootCmd.AddCommand(subCmd2) // Execute the root command if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }

Keywords: Cobra Go nested subcommands CLI command line interface programming