62

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

Steven D
  • 46,160
Renjith G
  • 5,888
  • 1
    See also http://superuser.com/questions/247127/what-is-and-in-linux/247131#247131 – Olli Feb 20 '11 at 15:55

6 Answers6

68

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

cjm
  • 27,160
36

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 a lot 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.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 8
    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
11

$?-The exit status of the last command executed.

$0-The filename of the current script.

$#-The number of arguments supplied to a script.

$$-The process number of the current shell. For shell scripts, this is the process ID under which they are executing.

Romeo Ninov
  • 17,484
3

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.

Barun
  • 2,376
  • 11
    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
0

$? provide us the execution status of last execute command on prompt. Value '0' denotes that the command was executed successfuly and '1' is for not success.

-2

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

Mat
  • 52,586
harika
  • 21