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.

- 2,530
- 3
- 27
- 45
1 Answers
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)
-
Can you explain this to me: if(4>5) return 255; else return -1; shows 255 in the terminal. While if(10>1) return 255; else return -1; Also shows 255 in the terminal – Saif Jun 18 '18 at 00:46
-
Suppose the program is complex enough to produce that much of error codes. – Saif Jun 18 '18 at 00:50
-
So, the upper limit to how many error codes we can return is `256` - using does 8 bits, after that the combination of the least significant 8 bits repeats itself. – Saif Jun 18 '18 at 00:53
-
Yes, no more than 255 - 0 is reserved for "success". – Jun 18 '18 at 00:56
-
(https://stackoverflow.com/questions/35457979/what-is-echo-in-linux-terminal) The answer by Chris Jester-Young has 128 as that number, so their system is using least significant 7 bits only. – Saif Jun 18 '18 at 00:56
-
As I said, please limit yourself to use values 1-126. If you need more than a handful, it's probably better to reconsider. – Jun 18 '18 at 00:58
-
128 is more than enough for me. :P – Saif Jun 18 '18 at 01:00