Cobra: How to access Persistent Flags values in init function?

Created on 3 Aug 2017  路  2Comments  路  Source: spf13/cobra

I want to have flag which depending on I'll change root command. I supposed to do it in init function, but flag values are not available before Execute() is ran.

Is there some way to get flag's value in init function?

To explain better, here is minimal example:

var MyVar bool

var something = &cobra.Command{
    Use:   "something",
}

func Execute() {    
    if err := something.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }   
}

func init() {
    //flags here
    something.PersistentFlags().BoolVarP(&MyVar, "flag", "f", false, "Anything")

    if MyVar {
             something.SetOutput(...)
        }
}

MyVar is always false before Execute happens. What can I do to make it available?

Most helpful comment

I don't think you can, usually I just find another approach other than trying to do it in init... usually I just do it in the Run func if at all possible

All 2 comments

I don't think you can, usually I just find another approach other than trying to do it in init... usually I just do it in the Run func if at all possible

See #510

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mdaymard picture mdaymard  路  5Comments

anentropic picture anentropic  路  4Comments

umbynos picture umbynos  路  5Comments

alapidas picture alapidas  路  3Comments

anuraaga picture anuraaga  路  5Comments