Example

In the example below, we have defined three commands. Two are at the top level
and one (cmdTimes) is a child of one of the top commands. In this case the root
is not executable meaning that a subcommand is required. This is accomplished
by not providing a ‘Run’ for the ‘rootCmd’.

We have only defined one flag for a single command.

More documentation about flags is available at https://github.com/spf13/pflag

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/spf13/cobra"
  6. )
  7. func main() {
  8. var echoTimes int
  9. var cmdPrint = &cobra.Command{
  10. Use: "print [string to print]",
  11. Short: "Print anything to the screen",
  12. Long: `print is for printing anything back to the screen.
  13. For many years people have printed back to the screen.`,
  14. Args: cobra.MinimumNArgs(1),
  15. Run: func(cmd *cobra.Command, args []string) {
  16. fmt.Println("Print: " + strings.Join(args, " "))
  17. },
  18. }
  19. var cmdEcho = &cobra.Command{
  20. Use: "echo [string to echo]",
  21. Short: "Echo anything to the screen",
  22. Long: `echo is for echoing anything back.
  23. Echo works a lot like print, except it has a child command.`,
  24. Args: cobra.MinimumNArgs(1),
  25. Run: func(cmd *cobra.Command, args []string) {
  26. fmt.Println("Print: " + strings.Join(args, " "))
  27. },
  28. }
  29. var cmdTimes = &cobra.Command{
  30. Use: "times [string to echo]",
  31. Short: "Echo anything to the screen more times",
  32. Long: `echo things multiple times back to the user by providing
  33. a count and a string.`,
  34. Args: cobra.MinimumNArgs(1),
  35. Run: func(cmd *cobra.Command, args []string) {
  36. for i := 0; i < echoTimes; i++ {
  37. fmt.Println("Echo: " + strings.Join(args, " "))
  38. }
  39. },
  40. }
  41. cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
  42. var rootCmd = &cobra.Command{Use: "app"}
  43. rootCmd.AddCommand(cmdPrint, cmdEcho)
  44. cmdEcho.AddCommand(cmdTimes)
  45. rootCmd.Execute()
  46. }

For a more complete example of a larger application, please checkout Hugo.