Take the 2-minute tour ×

When going through one shell script, I saw the term "$?". What is the significance of this term?

share|improve this question

4 Answers 4

$? expands to the exit status of the most recently executed foreground pipeline. See the Special Parameters section of the Bash manual.

In simpler terms, it's the exit status of the last command.

share|improve this answer

Cjm's answer is correct, but $? can be used in silly ways in shell scripts, and I'd like to warn against that. A lot of bad shell scripts have a repeated pattern of code:


if [ "$EXIT_STATUS" -eq "0" ]
    # Do work when command exists on success
    # Do work for when command has a failure exit

If at all possible (readability concerns sometimes intrude) you should code this situation differently:

if run_some_command
    # Do work when command exists on success
    # Do failure exit work

This latter usage is faster, does not contaminate the shell's variable namespace with what amounts to temp variables, can often be alot more readable for humans and encourages the use of "positive logic", the practice of writing conditionals without negations, which has cognitive simplicity in most situations. It does away with the use of $? for the most part.

share|improve this answer
More complicated syntax is necessary when there's more possibilities than just 0 or 1 — programs often communicate useful information through exit codes. And it's also useful if you need to re-use that value later on in the code (for logging, for example). –  mattdm Feb 20 '11 at 20:42

In addition to what cjm said, if the value of $? is 0, then the previous process did terminate normally (or successfully). Otherwise there was some error.

share|improve this answer
It doesn't always signal an error. diff exits with a 0 if the compared files are the same, with a 1 if they are different, and 2 is an error. –  Shawn J. Goff Feb 20 '11 at 15:04
It never signals an error. It's only the exit status of the previous command. The "0 if normal exit" thing is a convention (EXIT_SUCCESS/EXIT_FAILURE) –  aviraldg Feb 20 '11 at 17:41

$? determines the exit status of the executed command. $ followed by numbers (e.g. $1, $2, etc.) represents the parameters in the shell script.

share|improve this answer
You might want to read the correct answer... –  jasonwryan Sep 2 '12 at 5:07

Your Answer


