This question already has an answer here:
- Meaning of $? in shell scripts 7 answers
I saw the code written somewhere online, and I wanted to know what exactly does "$?" do/give us. Googling did not help.
Here's the code I saw it in:
#!/bin/sh
ping -c 2 localhost
if [ $? != 0 ] ; then
echo "Couldn't ping localhost, weird"
fi
ping -c 2 veryweirdhostname.noend
if [ $? != 0 ] ; then
echo "Surprise, Couldn't ping a very weird hostname.."
fi
echo "The pid of this process is $$"
Taken from: http://efod.se/writings/linuxbook/html/shell-scripts.html
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:
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
$?
.It's the return code from the most recently executed command.
By convention 0 is a successful exit and non-zero indicates some kind of error.
$?
is a variable holding the return value of the last command you ran.Example C program (
example.c
):Example Bash:
the other answers cover bash pretty well, but you don't specify a shell in your question. In csh (and tcsh)
$?
can be used to query the existence of variables, e.g.This special variable shows the exit status of the last command that was run in a script or command-line. For example, in a command-line, the user could type
The output would then be
This shows the output of who and the exit status of the command. A script would be the same.
Output: 0