What is the $? (dollar question mark) variable in shell scripting?

David Mulder picture David Mulder · Jul 26, 2011 · Viewed 156.2k times · Source

I'm trying to learn shell scripting, and I need to understand someone else's code. What is the $? variable hold? I can't Google search the answer because they block punctuation characters.

Answer

Poomalairaj picture Poomalairaj · Jul 26, 2011

$? is used to find the return value of the last executed command. Try the following in the shell:

ls somefile
echo $?

If somefile exists (regardless whether it is a file or directory), you will get the return value thrown by the ls command, which should be 0 (default "success" return value). If it doesn't exist, you should get a number other then 0. The exact number depends on the program.

For many programs you can find the numbers and their meaning in the corresponding man page. These will usually be described as "exit status" and may have their own section.