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.
var Verbose bool
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.
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.
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.
command := cobra.Command{
Use: "print [OPTIONS] [COMMANDS]",
TraverseChildren: true,
}
Bind Flags with Config
You can also bind your flags with viper:
var author string
func init() {
rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
}
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:
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
rootCmd.MarkFlagRequired("region")