Read a command exit status
What is an exit status?
When a command finishes, it provides an exit status: a number used to communicate success or another outcome. In shell conventions, zero means success (or a true condition) and nonzero means some other outcome, often failure or a false condition. A specific nonzero value depends on the command’s contract. Bash records the status of the most recently completed foreground pipeline; at this stage, each example uses simple commands.
trueprintf '%s\n' "$?"falseprintf '%s\n' "$?"Expected output when executed:
01The built-in true succeeds without printing anything; false returns 1 without printing anything. $? is a special parameter that expands to the previous status. Double quotes preserve the expanded value as one argument; printf then prints it. Run these examples in ordinary Bash with the default error-handling options (in particular, errexit off).
Read the status immediately
falseprintf '%s\n' 'A later message'printf '%s\n' "$?"Expected output when executed:
A later message0The final line is 0, not 1: the intervening successful printf replaced the status of false. If you want to inspect a command’s result, read $? immediately afterward. A later lesson explains how to save the number in a variable.
A script also has a status
bash -c 'printf "%s\n" "Task reported"; false'printf '%s\n' "$?"Expected output when executed:
Task reported1The semicolon separates two commands in the supplied command string. The child Bash prints a message and then runs false. Without an explicit exit or other special termination, Bash returns the status of the last command it executes. Printing a message does not imply that the script succeeded. This distinction will be central when you learn conditions and automation.
Practice
In an ordinary Bash session, run false, print its status immediately, then run true and print its status. Predict what changes if you insert a successful printf between false and the status check.
Next chapter: Variables and environment.