Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices on setting exit status codes

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?

like image 353
helpermethod Avatar asked Jun 01 '15 08:06

helpermethod


People also ask

What is a successful exit code?

# By convention, an 'exit 0' indicates success, #+ while a non-zero exit value means an error or anomalous condition.

What are valid exit statuses?

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.

How do you use exit codes?

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.

What is exit status How do you check the exit status?

“$?” 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.


1 Answers

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.

like image 61
Mureinik Avatar answered Sep 30 '22 18:09

Mureinik