Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "$?" give us exactly in a shell script? [duplicate]

Tags:

linux

bash

shell

sh

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

like image 773
Khushman Patel Avatar asked Sep 12 '11 03:09

Khushman Patel


People also ask

What does $? Mean in shell script?

$? = was last command successful. Answer is 0 which means 'yes'. Follow this answer to receive notifications.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.


2 Answers

$? 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 
like image 143
Brendan Long Avatar answered Oct 05 '22 08:10

Brendan Long


Most of the answers are missing a bit of detail. A definitive answer is found in the POSIX standard for the shell, in the section on special parameters:

$? Expands to the decimal exit status of the most recent pipeline (see Pipelines ).

Don't be surprised by the word pipeline, because even a simple command such as ls is grammatically a pipeline consisting of a single command. But then, what is $? for a multi-command pipeline? It's the exit status of the last command in the pipeline.

And what about pipelines executing in the background, like grep foo bigfile|head -n 10 > result &?

Their exit status can be retrieved through wait once the pipeline's last command has finished. The background process pid is available as $!, and $? only reports whether the background command was correctly started.

Another detail worth mentioning is that the exit status is usually in the range 0 through 255, with 128 to 255 indicating the process exited due to a signal. Returning other values from a C program is likely to not be reflected accurately in $?.

like image 22
Jens Avatar answered Oct 05 '22 09:10

Jens