When implementing my own scripts, is it the best practice to exit with different exit codes for different failure scenarios? Or should I just return exit code 1 for failure and 0 for success providing the reason on stderr?
# By convention, an 'exit 0' indicates success, #+ while a non-zero exit value means an error or anomalous condition.
The exit status of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task. In DOS, this may be referred to as an errorlevel.
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred. The bash sets “$?” To the exit status of the last executed process.
Providing a descriptive error message to stderr is fine and well for interactive users, but if you expect your scripts to be used by other scripts/programs, you should have distinctive error codes for different failures, so the calling script could make an informed decision on how to handle the failure.
If the calling program does not wish to handle different failures differently it could always check the return code against > 0
- but don't assume this is the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With