Special variables (Bash)
Bash has so-called special variables, that provide information about the state of the shell or commands, not to be confused with positional arguments:
$?
: The exit status of the last command executed$$
: The process ID (PID) of the current shell$!
: The PID of the last background process$_
: The last argument of the previous command$-
: The current shell options (e.g., options set by set command)IFS
: The Internal Field Separator, not positional but frequently used for splitting strings.
Exit status code - $?
The exit status or exit status code is a numerical value returned by a program or command (e.g., a comparison) when it finishes running, and stored in special variable $?
. It provides for the system or scripts to understand the outcome of execution, typically indicating whether it ran successfully or encountered an error. A code of 0 usually indicates success, while any other code some shade of failure. I suspect these codes are not consistently applied, though:
0
: A status code of 0 usually means that the program or command ran successfully, with no error1
: A generic error2
: Incorrect usage or missing argument127
: Command not found
Volatile
An exit code is a volatile thing: As soon as you execute a new command, the status of the previous command will be overwritten.
Example:
wp plugin is-installed blub echo "exit status: $?" echo "exit status: $?"
Generates output
1 0
where
1
is the exit status of thewp plugin
command0
is the exit status of the firstecho
command.
Advantages of using status codes
The use of status codes allow you to check the success or failure of a command independently of its output. This is especially useful when:
- The command produces a lot of output: You can focus only on whether it succeeded or failed without needing to parse or interpret the output
- Silent or verbose commands: Some commands might not output anything at all (or may only output errors), but you can still check their status with the exit code
- Automating error handling: Scripts can reliably act on the exit code to handle different situations (e.g., retrying a command, logging an error, or taking corrective action) without worrying about inconsistencies in output.
Examples
See Wp plugin is-installed (WP-CLI) for some examples.