Most of the answers are missing a bit of detail. A definitive answer is found in the POSIX standard for the shell, in the section on special parameters:
$? Expands to the decimal exit status of the most recent pipeline
(see Pipelines ).
Don't be surprised by the word pipeline, because even a simple command such as ls
is grammatically a pipeline consisting of a single command. But then, what is $?
for a multi-command pipeline? It's the exit status of the last command in the pipeline.
And what about pipelines executing in the background, like grep foo bigfile|head -n 10 > result &
?
Their exit status can be retrieved through wait
once the pipeline's last command has finished.
The background process pid is available as $!
, and $?
only reports whether the background command was correctly started.
Another detail worth mentioning is that the exit status is usually in the range 0 through 255, with 128 to 255 indicating the process exited due to a signal. Returning other values from a C program is likely to not be reflected accurately in $?
.