Search code examples
basherror-handlingcompiler-errorsechoexit

Why echo $? returns different value than expected?


I know that echo $? returns the exit status of the previous process. In my program I get 0 if my program ends with a status code of 0. But when the program ends with status code -1 echo $? shows 255. Similar questions are there on StackOverflow, but is not explained why is it so. Plus one of the answers says generally values above 128 indicates some error and negative exit code. Like for example, 147 - we can get the real exit code by subtracting 128 from 147, 128 - 147 = -19, so the exit code was -19. In my computer I find 256 as that number. For example 255 - 256 = -1, which was what my program was returning. Why on different systems do these numbers vary 128, 256 and why can't they print the original negative code instead of adding these numbers to the original exit status code.


Solution

  • For historical reasons, exit code is interpreted as unsigned one-byte value. "Normal" error codes are positive (<127), while "abnormal" error codes (e.g. those produced by terminating on signal) are negative (>=128).

    Try pressing Ctrl-C on a sleep 10 command. The exit code is 130.

    127 is the result of "command not found".

    It's really not a recommended practice to use negative error codes explicitly.

    For more information, take a look at wait() man page (man 2 wait), in particular WFEXITED() and friends.

    WEXITSTATUS(status)

    returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.

    (Emphasis added)