How to Get Exit Status Codes from Linux Command Prompt
/* Posted December 24th, 2008 at 8:15am *//* Filed under How-To, Linux, Programming */
/* */

Whenever you execute a command in Linux, the command actually returns an exit status code which is useful when you need information on how the execution went like if it failed or succeeded. An exit status code of:
- 0 means the command executed properly without any errors
- 1 means the command executed but there may have been some minor issues (think of these as warnings)
- 2 means the command executed and there was a major problem (think of these as errors)
- Getting the exit codes is easy, simply execute any command in Linux. Immediately after, to check its exit status, type
echo $?
and you will see a number printed, which will be 0, 1, or 2. For example, check out this procession:
% whoami
coderetard
% echo $?
0
This means the command ‘whoami’ ran with an exit code of 0, meaning its exit status was OK. Now check this out:
% cd dir_that_does_not_exist
dir_that_does_not_exist: No such file or directory.
% echo $?
1
It looks like that didn’t go too smoothly!
To take it even further, make sure your own programs are returning accurate status codes to reflect the exit status. In C, you would do something like this:
#include <stdlib.h>
void func_ok()
{
// exit code = 0
exit(EXIT_SUCCESS);
}
void func_fail()
{
// exit code = 1
exit(EXIT_FAILURE);
}
int main()
{
func_ok();
//func_fail();
}
And basically you would exit with EXIT_SUCCESS if everything ran OK, otherwise you would exit with EXIT_FAILURE. This method is preferred over giving an integer value directly into the exit() function as using stdlib macros are more portable across platforms.
Image/Flickr/Biappi
















