Skip to content

Conversation

@maishivamhoo123
Copy link

Description

Addresses issue #2338.

Currently, cmd --help returns exit code 0. This causes scripts using eval $(cmd) to crash because the shell tries to execute the help text as commands. This PR allows developers to set a custom exit code (e.g., 2) when help is invoked, preventing this behavior.

Changes

  • Added helpExitCode field to Command struct.
  • Added SetHelpExitCode(int) method.
  • Updated ExecuteC to return a specific error if helpExitCode is set and help is invoked.
  • Added unit test TestHelpExitCode.

Example Usage

rootCmd.SetHelpExitCode(2)
// Running "app --help" will now print usage and exit with code 2

@CLAassistant
Copy link

CLAassistant commented Jan 8, 2026

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

@ccoVeille ccoVeille left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won't work the way you think.

It won't return the expected exit code.

It will only return exit 1 and an error message.

Note: I'm not saying the feature is a bad idea (or a good one).

I'm just saying it doesn't do work

@maishivamhoo123
Copy link
Author

@ccoVeille Thank you for the guidance! I've updated the logic to use a custom ExitError struct. This ensures the specific integer code can be retrieved via errors.As instead of defaulting to a generic error 1.

Apologies for the oversight in the previous commit. I would appreciate your review when you have a moment.
Looking for guidance.
Thank you sir.

@ccoVeille
Copy link
Contributor

This won't work either...

Take a look at CheckErr method and how code use it.

I feel like your PR requires more iterations. Adding a feature like this to such a project might not be easy.

let's wait for @marckhouzam and his feedback

But if you have a need for this, maybe you could simply consider defining a custom helper command to your code using cobra (so without change in cobra) and then call os.Exit with the code you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants