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?
4 Answers
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
-
6Every UNIX shell I have access to uses
$?
to indicate the last program's return code. This includes not justbash
but also standard Bourne shell,ksh
,csh
, andzsh
. Pretty much every UNIX shell in existence agrees on this one.– cleeMay 23, 2011 at 6:42 -
The shell he's using in Linux is almost certainly
bash
, but$?
oringinates from the Bourne shell.– GabeMay 23, 2011 at 6:47 -
@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.– troelsknMay 23, 2011 at 10:32
-
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.
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.