Skip to content

Correct pattern for exiting a command with a non zero return code #2124

Open
@tomqwpl

Description

@tomqwpl

I'm trying to establish what the correct pattern is for exiting a command with a non zero return code.

I can use RunE, but the normal effect of that is that the "usage" is printed out, since there's no distinction between an error from validating the args (where you would want usage to result) and an error from the operation of your command. You can SilenceUsage, but then you get no usage help on invalid args either, so that doesn't feel like the right way.

The examples generated by the CLI all use Run instead of RunE. The implication would appear to be that I have to manually os.Exit(1) if I want my command to "fail" and return a non zero return code. But that feels wrong, it's going to skip all of the post run actions etc.

Looking at a couple of examples, it seems like managing an exit code outside of cobra seems to be a solution used in a few places, so letting the command run to completion and then once cobra has returned calling os.Exit() with the value that's stored in some global variable somewhere.

What's the idiomatic usage here?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions