3

This question already has an answer here:

In my terminal it printed out a seemingly random number 127. I think it is printing some variable's value and to check my suspicion, I defined a new variable v=4. Running echo $? again gave me 0 as output.

I'm confused as I was expecting 4 to be the answer.

marked as duplicate by Rui F Ribeiro, Fabby, jimmij, Christopher, heemayl Feb 17 at 11:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

From man bash:

$? Expands to the exit status of the most recently executed foreground pipeline.

echo $? will return the exit status of last command. You got 127 that is the exit status of last executed command exited with some error (most probably). Commands on successful completion exit with an exit status of 0 (most probably). The last command gave output 0 since the echo $v on the line previous finished without an error.

If you execute the commands

v=4
echo $v
echo $?

You will get output as:

4 (from echo $v)
0 (from echo $?)

Also try:

true
echo $?

You will get 0.

false
echo $?

You will get 1.

The true command does nothing, it just exits with a status code 0; and the false command also does nothing, it just exits with a status code indicating failure (i.e. with status code 1).

3

$? is useful in shellscripts as a way to decide what to do depending on how the previous command worked (checking the exit status). We can expect that the exit status is 0 when the previous command worked (finished successfully), otherwise a non-zero numerical value.

Demo example:

#!/bin/bash

patience=3

read -t "$patience" -p "Press 'Enter' if you run Unix or Linux, otherwise press 'ctrl+d' "

status="$?"

if [[ $status -eq 0 ]]
then
 echo "That's great :-)"
elif [[ $status -eq 1 ]]
then
 echo "(exit status=$status)
You are welcome to try Unix or Linux :-)"
else
 echo "(exit status=$status)
You did not answer within $patience seconds. Anyway :-)"
fi
echo "'Unix & Linux' is a question/answer web site for
Unix and Linux operating systems"

You may ask how to run a bash shellscript without Unix or Linux ;-)

  • 1
    Except that in most cases you can use the command directly in the if-condition, i.e.: if cmd ... ; then, instead of cmd ...; if [[ $? -eq 0 ]]; then. You really only need $? if you need to tell apart three different exit codes. – ilkkachu Feb 17 at 10:30
  • @ilkkachu, You are right, and I will modify the demo example according to your comment :-) – sudodus Feb 17 at 10:32
  • You may ask how to run a bash shellscript without Unix or Linux - with a she-bang! ofcourse – Weezy Feb 17 at 11:05

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