What is meant by "$?" in shell?

6

1

I am using Debian 6.0. I know the regular command line arguments but couldn't find what $? is meant for? Does anyone have an idea of what is meant by $? in Linux shell?

Ravi

Posted 2011-05-23T06:35:16.443

Reputation:

Answers

15

bash, not shell. (Bash is but one of several possible shells. It is the most common though)

It means the exit code of the last command that executed.

See here: http://tldp.org/LDP/abs/html/othertypesv.html and here http://tldp.org/LDP/abs/html/exit-status.html

troelskn

Posted 2011-05-23T06:35:16.443

Reputation: 371

6Every UNIX shell I have access to uses $? to indicate the last program's return code. This includes not just bash but also standard Bourne shell, ksh, csh, and zsh. Pretty much every UNIX shell in existence agrees on this one. – clee – 2011-05-23T06:42:51.383

The shell he's using in Linux is almost certainly bash, but $? oringinates from the Bourne shell. – Gabe – 2011-05-23T06:47:37.010

@clee You're right. Guess it was a knee-jerk reaction I have to people not aware that there is a difference between shell and bash. – troelskn – 2011-05-23T10:32:47.010

Well, Bash is a shell as well. – Ugo – 2011-05-23T13:30:06.590

5

For shells supporting this shell variable "$?" contains the return code of a command executed most recently.

So if you're running program "abc" which returns 1 on exit doing

$ echo $?

gives "1" - the return code.

And it is not only available in bash, also other shells have this feature.

Marcin Cylke

Posted 2011-05-23T06:35:16.443

Reputation: 171

2

The return code of the last executed program.

El Yobo

Posted 2011-05-23T06:35:16.443

Reputation: 121

0

Wow, they have mentioned that it is the return code of the last executed program, but no one mentioned that if it's more than 0 it's probably indicating an error. It is general practice that when a program or script executes without error it returns a value of 0 to indicate that it has finished with no errors. Not all programs and scripts do, but they should.

Checking the value of $? after running a linux command should tell you if there were errors or not. Check the docs of each program to know what the possible return values are. Some won't return a value but most do. In your scripts you should end with 'return X' where X is some value 0=good/no errors and anything greater than zero indicates some problem occurred. Even if all you use are values of 0 or 1 it's good practice. This allows other scripts to know whether the next line/command should be executed based on the success or failure of the last command. It makes for smarter scripting and better control.

user817752

Posted 2011-05-23T06:35:16.443

Reputation: 31