What does echo $? do?

48,106

Solution 1

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).

Solution 2

$? 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 ;-)

Share:
48,106

Related videos on Youtube

Weezy
Author by

Weezy

Updated on September 18, 2022

Comments

  • Weezy
    Weezy almost 2 years

    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.

  • ilkkachu
    ilkkachu over 5 years
    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.
  • sudodus
    sudodus over 5 years
    @ilkkachu, You are right, and I will modify the demo example according to your comment :-)
  • Weezy
    Weezy over 5 years
    You may ask how to run a bash shellscript without Unix or Linux - with a she-bang! ofcourse