What is the definition of $? in a shell script?

When experiencing one shell script, I saw the term "$?". What is the value of this term?

0
2019-05-18 22:09:59
Source Share
Answers: 3

$? increases to the exit standing of one of the most lately implemented foreground pipe. See the Special Parameters section of the Bash manual.

In less complex terms, it is the exit standing of the last command.

0
2019-05-21 08:23:09
Source

In enhancement to what cjm said, if the value of $? is 0, after that the previous procedure did end generally (or efficiently). Or else there was some mistake.

0
2019-05-21 06:22:20
Source

Cjm's answer is proper, yet $? can be made use of in foolish methods covering manuscripts, and also I would certainly such as to advise versus that. A great deal of negative covering manuscripts have a repetitive 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 in all feasible (readability problems occasionally intrude) you need to code this scenario in different ways:

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

This last use is much faster, does not infect the covering varies namespace with what total up to temp variables, can usually be a whole lot extra legible for human beings and also urges making use of "favorable reasoning", the technique of creating conditionals without negations, which has cognitive simpleness in the majority of scenarios. It gets rid of making use of $? essentially.

0
2019-05-21 05:38:59
Source