When going through one shell script, I saw the term "$?". What is the significance of this term?
$? 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'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.
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.