spf13 / cobra

A Commander for modern Go CLI interactions
https://cobra.dev
Apache License 2.0
37.8k stars 2.83k forks source link

Cobra does not exit when help or version flag is passed #2175

Closed Cynnexis closed 2 months ago

Cynnexis commented 2 months ago

I use Cobra to parse the arguments (I don't use any commands), but I notice that when --help or --version is passed to my program, it keeps running after displaying the usage or the version.

I don't want the program to run with those arguments, but I don't see any information about how to detect these arguments in the Cobra documentation (they are automatically generated), and how to stop the program if passed.

Is there a way to easily exit the program when --help or --version is passed?

Cynnexis commented 2 months ago

The solution is to get the value after the rootCommand.Execute():

helpVal, err := rootCmd.Flags().GetBool("help")
if err != nil {
    return err
}

versionVal, err := rootCmd.Flags().GetBool("version")
if err != nil {
    return err
}

if helpVal || versionVal {
    os.Exit(0)
}