then - linux $?




What does “$?” give us exactly in a shell script? (4)

I saw the code written somewhere online, and I wanted to know what exactly does "$?" do/give us. Googling did not help.

Here's the code I saw it in:

#!/bin/sh

ping -c 2 localhost
if [ $? != 0 ] ; then
    echo "Couldn't ping localhost, weird"
    fi

ping -c 2 veryweirdhostname.noend 
if [ $? != 0 ] ; then
    echo "Surprise, Couldn't ping a very weird hostname.."
    fi

echo "The pid of this process is $$"

Taken from: http://efod.se/writings/linuxbook/html/shell-scripts.html

https://code.i-harness.com


$? is a variable holding the return value of the last command you ran.

Example C program (example.c):

int main() { return 1; }

Example Bash:

gcc -o example example.c
./example
echo $? # prints 1

It's the return code from the most recently executed command.

By convention 0 is a successful exit and non-zero indicates some kind of error.


This special variable shows the exit status of the last command that was run in a script or command-line. For example, in a command-line, the user could type

 who; echo $?

The output would then be

 user  tty7         2014-07-13 19:47
 0

This shows the output of who and the exit status of the command. A script would be the same.

 #!/bin/bash
 who
 echo $?

Output: 0


the other answers cover bash pretty well, but you don't specify a shell in your question. In csh (and tcsh) $? can be used to query the existence of variables, e.g.

if $?my_var then
    echo my_var exists
endif






sh