Meaning of $? (dollar question mark) in shell scripts
What does
echo $?
mean in shell programming?
This is the exit status of the last executed command.
For example the command true
always returns a status of 0
and false
always returns a status of 1
:
true
echo $? # echoes 0
false
echo $? # echoes 1
From the manual: (acessible by calling man bash
in your shell)
$?
Expands to the exit status of the most recently executed foreground pipeline.
By convention an exit status of 0
means success, and non-zero return status means failure. Learn more about exit statuses on wikipedia.
There are other special variables like this, as you can see on this online manual: https://www.gnu.org/s/bash/manual/bash.html#Special-Parameters
$?
returns the exit value of the last executed command. echo $?
prints that value on console. zero implies a successful execution while non-zero values are mapped to various reason for failure.
Hence when scripting; I tend to use the following syntax
if [ $? -eq 0 ]; then
# do something
else
# do something else
fi
The comparison is to be done on equals to 0
or not equals 0
.
** Update Based on the comment: Ideally, you should not use the above code block for comparison, refer to @tripleee comments and explanation.
echo $? - Gives the EXIT STATUS of the most recently executed command . This EXIT STATUS would most probably be a number with ZERO implying Success and any NON-ZERO value indicating Failure
? - This is one special parameter/variable in bash.
$? - It gives the value stored in the variable "?".
Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) .