var cmdPrint = &cobra.Command{ Use: "Print [string to print]", Short: "Print anything to the screen", Long: `print is for printing anything back to the screen. For many years people have printed back to the screen.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, }
var cmdEcho = &cobra.Command{ Use: "echo [string to echo]", Short: "Echo anything to the screen", Long: `echo is for echoing anything back. Echo works a lot like print, except it has a child command.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, }
var echoTimes int var cmdTimes = &cobra.Command{ Use: "time [# times] [string to echo]", Short: "Echo anything to the screen more times", Long: `echo things multiple times back to the user y providing a count and a string.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for i := 0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, }
funcinit() { cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") cmdEcho.AddCommand(cmdTimes) }
Available Commands: Print Print anything to the screen completion Generate the autocompletion script for the specified shell echo Echo anything to the screen help Help about any command
Flags: -h, --helphelpfor app
Use "app [command] --help"for more information about a command.
可以看到Available Commands有四个命令,试试 echo 这个命令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
(base) ***@shenjian pro_1_example % ./app echo -h echo is for echoing anything back. Echo works a lot like print, except it has a child command.
Usage: app echo [string to echo] [flags] app echo [command]
Available Commands: time Echo anything to the screen more times
Flags: -h, --helphelpforecho
Use "app echo [command] --help"for more information about a command.
可以看到Usage 选项有两个方法,而且里面还有一个子命令 time。看看 time 是怎么使用的:
1 2 3 4 5 6 7 8 9 10 11
(base) luliang@shenjian pro_1_example % ./app echo time -h echo things multiple times back to the user y providing a count and a string.
Usage: app echo time [# times] [string to echo] [flags]
Flags: -h, --helphelpfor time -t, --times int times to echo the input (default 1)