Python Exit Codes ($?), Error Handling & Custom Exits
Every command, binary, and script in Unix returns an integer Exit Status (Exit Code) between 0 and 255 upon termination. By universal standard, `0` signifies success, while any non-zero value (`1–255`) indicates an error or failure condition. The special parameter `$?` captures the exit code of the most recently executed command.
"An exit code is like a doctor's report at the end of an examination: `0` is a clean bill of health; any number > 0 specifies the exact medical code for what went wrong."
Deep Dive: How It Works
Special Variable `$?`: Immediately stores the exit status of the previous foreground command.
Standard Conventions: `0` (Success), `1` (General error), `2` (Misuse of shell builtins), `126` (Command invoked cannot execute / permission denied), `127` (Command not found), `130` (Terminated by Ctrl+C / SIGINT 128+2).
The `exit` Command: `exit 0` ends the script with success; `exit 1` ends with error.
Syntax Blueprint
command
if [[ $? -ne 0 ]]; then
echo "Command failed with code $?"
exit 1
fi
# Or idiomatic short-circuit:
command || { echo "Failed"; exit 1; }Inspect $? immediately after running a command or use short-circuit logic ||.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Running `echo $?` followed by `if [ $? -eq 0 ]`.Why it happens: The `echo` command succeeds, resetting `$?` to 0 before the `if` statement can test it.
How to fix: Save `$?` to a variable immediately: `STATUS=$?; echo "Status: $STATUS"; if [ $STATUS -eq 0 ]...`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Capture and Test an Exit Code
Run `true` (a command that always succeeds with 0).
Capture `$?` into `CODE=$?`.
Echo "Exit Code: $CODE".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.