What does echo $? do?
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
).
$?
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 ;-)