Cobra: Exit status control

Created on 11 Jan 2016  Â·  3Comments  Â·  Source: spf13/cobra

Any chance I could register a callback to handle os.Exit myself when the user stuffs up on flag usage? I need more control over the exit status than your hard-coded os.Exit(-1) permits.

Most helpful comment

The err result from RootCmd.Execute gets RunE and command line problems e.g. unknown options, which is nice… aah, and the undocumented SilenceUsage suppresses the usage text. Awesome.

TL;DR:

// control your exit status with Execute, by default in cmd/root.go:
func Execute() {
    if err := RootCmd.Execute(); err != nil {
        // log it, then
        os.Exit(23)
    }
}

All 3 comments

Hang on… that'd be PersistentPreRunE, perhaps. Or do I need to hook all the E functions?

I did a clean-up of Hugo in this area some time ago, have a look at

https://github.com/spf13/hugo/blob/master/commands/hugo.go#L126
https://github.com/spf13/hugo/blob/master/commands/hugo.go#L100

To propagate errors from the commands, use the RunE.

The err result from RootCmd.Execute gets RunE and command line problems e.g. unknown options, which is nice… aah, and the undocumented SilenceUsage suppresses the usage text. Awesome.

TL;DR:

// control your exit status with Execute, by default in cmd/root.go:
func Execute() {
    if err := RootCmd.Execute(); err != nil {
        // log it, then
        os.Exit(23)
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jjzcru picture jjzcru  Â·  3Comments

rogercoll picture rogercoll  Â·  5Comments

anentropic picture anentropic  Â·  4Comments

anuraaga picture anuraaga  Â·  5Comments

supershal picture supershal  Â·  4Comments