Linux Basics: Using Bash Exit Status
A command reports an exit status separately from the text it prints. In Bash on Debian and Ubuntu, zero normally means success and a nonzero value signals another outcome. Checking that status helps you decide whether to continue a sequence of commands.
Read the previous status
true
printf '%s\n' "$?"
false
printf '%s\n' "$?"0
1true returns zero, while false returns one. Bash expands $? to the status of the most recently completed command.
Check it immediately. Even a successful printf replaces the previous status, so another command between the operation and the check can hide the result you wanted.
A nonzero value needs context: grep uses one for no matching lines, while larger values indicate an error. Check the relevant command’s documentation.
Continue only after success
Run mktemp -d, then use cd to enter the temporary directory it prints.
mkdir notes && printf 'Directory created\n'&& runs the command on its right only when the command on its left succeeds. If the directory already exists, this mkdir fails and the message is skipped.
Choose a fallback
[ -f notes/todo.txt ] || printf 'No regular todo file yet\n'|| runs the right-hand command only after a nonzero status. Here, the test checks whether the path identifies a regular file. Spaces around [ and ] are required.
For pipelines, Bash normally reports the last command’s status. A successful final command can hide an earlier failure. Do not assume a pipeline’s zero status proves every stage succeeded.
Reference
Acknowledgements
This post was created with assistance from AI.
Linux Basics — lesson 12 of 25. Series index
Previous: Using Environment Variables · Next: Creating Symbolic Links