36

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

43

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

26

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.

  • 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
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.

  • 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
3

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

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
    Not only at the interactive prompts, but in scripts too, and any non-zero value signifies failure. – Kusalananda Apr 25 '18 at 11:39
-3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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