Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

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
8  
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
2  
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

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:

run_some_command
EXIT_STATUS=$?

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

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

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

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
5  
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

$? 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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.