Working with Flags

Flags provide modifiers to control how the action command operates.

Assign flags to a command

Since the flags are defined and used in different locations, we need to
define a variable outside with the correct scope to assign the flag to
work with.

  1. var Verbose bool
  2. var Source string

There are two different approaches to assign a flag.

Persistent Flags

A flag can be ‘persistent’ meaning that this flag will be available to the
command it’s assigned to as well as every command under that command. For
global flags, assign a flag as a persistent flag on the root.

  1. rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")

Local Flags

A flag can also be assigned locally which will only apply to that specific command.

  1. rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")

Local Flag on Parent Commands

By default Cobra only parses local flags on the target command, any local flags on
parent commands are ignored. By enabling Command.TraverseChildren Cobra will
parse local flags on each command before executing the target command.

  1. command := cobra.Command{
  2. Use: "print [OPTIONS] [COMMANDS]",
  3. TraverseChildren: true,
  4. }

Bind Flags with Config

You can also bind your flags with viper:

  1. var author string
  2. func init() {
  3. rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
  4. viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
  5. }

In this example the persistent flag author is bound with viper.
Note, that the variable author will not be set to the value from config,
when the --author flag is not provided by user.

More in viper documentation.

Required flags

Flags are optional by default. If instead you wish your command to report an error
when a flag has not been set, mark it as required:

  1. rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
  2. rootCmd.MarkFlagRequired("region")