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

Tags:


Related Stories


Nothing found for Tools Panel Php?preblock=%3Cdiv+class%3D%22sidelist%22%3E%3Cul%3E&postblock=%3C%2Ful%3E%3C%2Fdiv%3E&preitem=%3Cli%3E&postitem=%3C%2Fli%3E&num=

Mission Statement

Mission Statement

To remain on the cutting edge of Internet advertising by investing and building innovative, progressive and revolutionary companies that advance the industry. It is our responsibility to operate companies that set new standards for service, quality, and profitability.

Read More

What We Do

We are committed to the pursuit of excellence and pledge to stand ahead of our competitors. Our business model is simple: find and cultivate ideas that improve every aspect of the experience, setting a new precedence. We thrive in competitive markets because we focus on strong, long-term relationships and innovative solutions. Our influence and reputation flows from the quality of our teams and...

Read More