Exit status
October 19th, 2006
Every single program or command has an exit status. If a command exits successfully it is 0, otherwise its greater than 0 and less than 255. That is to say that 0 is true and everything else is false. The exit status of a command is stored in the variable $?. See the example below:
root@www:~ # true
root@www:~ # echo $?
0
root@www:~ # false
root@www:~ # echo $?
1
The true command always exits with a value of 0 while the false command always exits with a value of 1. While the usefulness of these commands may not be obvivous, its a great way to make sure you have either a 0 or > 0 exit status.
If a specific command does not succeeed it does not matter if its exit value is 1, 2, or 123. All values except 0 are false. For example, both commands below are being ran incorrectly. They both need arugments.
root@www:~ # kill
kill: usage: kill [-s sigspec | -n signum | -sigspec] [pid | job]... or kill -l [sigspec]
root@www:~ # echo $?
1
root@www:~ # curl
curl: try 'curl --help' or 'curl --manual' for more information
root@www:~ # echo $?
2
However, if we use kill correctly, its exit value with be 0.
root@www:~ # sleep 10 &
[1] 24110
root@www:~ # kill -9 24110
root@www:~ # echo $?
0
[1]+ Killed sleep 10
In the same vein if we use curl correctly it will exit 0.
root@www:~ # curl http://bashcurescancer.com/feed/
root@www:~ # echo $?
0
For further discussion see Command Lists Logical Operators.


Leave a Reply