Lesson 23 of 60 · Go
Building a CLI with Cobra
Duration: 20 minutes
Cobra CLI Framework
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Cobra powers kubectl, git, and many other tools.
package main
import (
"fmt"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{ Use: "app", Short: "Demo CLI" }
var helloCmd = &cobra.Command{
Use: "hello [name]",
Short: "Print a greeting",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", args[0])
},
}
func init() { rootCmd.AddCommand(helloCmd) }
func main() { rootCmd.Execute() }
Run it:
$ go run main.go hello World
Hello, World!
Persistent flags
rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Enable verbose output")