Determine if flags were actually passed in (sub)command invocation in golang's cobra/viper

I have a cobra command

var mycommandCmd = &cobra.Command{
    Use:   "mycommand",
    PersistentPreRunE: func(cmd *cobra.Command, args []string) error {

and a subcommand

var mysubcommandCmd = &cobra.Command{
    Use:   "mysubcommand",
    Args:  cobra.ExactArgs(1),
    RunE: func(cmd *cobra.Command, args []string) error {

which I of course bind together


I also have some flags for both of them

mycommandCmd.PersistentFlags().BoolP("foo", "", true, "Whether to foo")
mysubcommandCmd.Flags().BoolP("foobar", "", true,  "Whether to foobar")

My question is the following:

Assuming the end go binary is named prog, is there a (cobra / viper) built in way of checking of whether any flags were actually passed during subcommand invocation?

i.e. how can I programmatically distinguish between this

prog mycommand mysubcommand --foobar

and this

prog mycommand mysubcommand

Checking against the default flag values will not work of course (and does not scale against the flag number)

>Solution :

You can do:


That should return if the flag was set, or if the default value was used.

Leave a Reply