Bash Exit Status
An exit status is a number a command leaves behind when it finishes. The number reports whether the command succeeded or failed.
Success leaves a zero
The true command always succeeds. Printing $? right after it shows 0.
true
echo $?Failure leaves a one
The false command always fails. Printing $? right after it shows 1.
false
echo $?A normal command can succeed
The echo command prints its line and succeeds. The status printed after it is 0.
echo "Backup copy made"
echo $?Example
true
echo $?
false
echo $?
echo "Back to work"
echo $?Key points
- Exit status: the number a command leaves behind when it ends.
- Status 0 means the command succeeded.
- A nonzero status means the command failed.
- $? holds the exit status of the last command that ran.
- true is a command that always ends with status 0.
- false is a command that always ends with status 1.
In this example, true ends first and the echo after it prints status 0. The false command ends next and the echo after it prints status 1. The third echo prints its text and succeeds. The final echo prints status 0 for that success.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does echo $? print right after the false command?