Reputation: 771
Could you guys help to give the algorithm used to generate $? in shell from exit code in program? For example,
$? is 1 for exit(1);
$? is 255 for exit(-1);
So I can infer exit code from $?
$? is 1 => exit code is 1
$? is 255 => exit code is -1
For something special,
$? is 0 for exit(256);
$? is 1 for exit(257);
Could anyone give the algorithm in shell used to generate $? with exit code, so that I can know the exit code only by observing $? after executing a command.
Thanks a lot.
Edit: To answer the question below, I added this example.
----a.c----
1 #include <stdlib.h>
2 int main()
3 {
4 exit(-1);
5 }
ning@m:~/work/02_test/ctest> gcc a.c
ning@m:~/work/02_test/ctest> ./a.out
ning@m:~/work/02_test/ctest> echo $?
255
ning@m:~/work/02_test/ctest>
Upvotes: 2
Views: 1105
Reputation: 3601
With bash, $? is the exit code of the last command. Running a shell script .
#!/bin/bash
exit 113
then echo $?
shows 113. See http://tldp.org/LDP/abs/html/exit-status.html for more info
With BASH there are some common exit codes.
The return value is just an 8bit Int. Exit codes 255 means out of range, so -1. The reason you are seeing 256->0 and 257->1 is it's wrapping around. Basically the exit value modulo 256.
All of this is true with Bash or C
Upvotes: 3