Meaning of $? (dollar question mark) in shell scripts


What does

echo $?

mean in shell programming?

This question is tagged with shell scripting special-characters

~ Asked on 2011-08-30 18:33:47

The Best Answer is


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:

echo $? # echoes 0
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:

~ Answered on 2011-08-30 18:35:39


$? 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
 # do something else

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.

~ Answered on 2014-12-16 09:21:31

Most Viewed Questions: