What is `$?` ? Is it a variable?

What is it?

$? is a built-in variable that stores the exit status of a command, function, or the script itself.

$? reads the exit status of the last command executed. After a function returns, $? gives the exit status of the last command executed in the function. This is Bash's way of giving functions a "return value." It returns 0 on success or an integer in the range 1 - 255 on error.

Are there others like it too?

Yes,there are several such built-in variables in bash. You can see a list here. Refer: http://www.tldp.org/LDP/abs/html/exit-status.html


$? is a variable but a special one, that's why special characters are allowed. ($?) Expands to the exit status of the most recently executed foreground pipeline.

It's not the only one, the shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed :

Variable    Meaning
$0          Filename of script
$1          Positional parameter #1
$2 - $9     Positional parameters #2 - #9
${10}       Positional parameter #10
$#          Number of positional parameters
"$*"        All the positional parameters (as a single word) *
"$@"        All the positional parameters (as separate strings)
${#*}       Number of positional parameters
${#@}       Number of positional parameters
$?          Return value
$$          Process ID (PID) of script
$-          Flags passed to script (using set)
$_          Last argument of previous command
$!          Process ID (PID) of last job run in background

* Must be quoted, otherwise it defaults to $@.

Sources:

  • http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters
  • http://tldp.org/LDP/abs/html/refcards.html#AEN22006

$? is a special shell parameter (variable).

In general all user defined variables must be named by using only the characters from character class [:alnum:] i.e. [a-zA-Z0-9_] (also can't begin with [0-9]).

In a nutshell, $? is a special variable (and there are quite a few of these) that can be considered as internal feature of the shell itself that provides the exit code of the previous command (whether succeded or failed).

You can read this to get more idea on variables.