What is Exit Status in Linux?
When you run a command in Linux, the system returns a short scorecard at the end called the exit status (or return code).
- 0 means the command completed successfully with no errors.
- A non-zero value means the command failed in some way.
A simple mapping:
- 0 = “All good!”
- 1 = “General error”
- 2, 127, 126, etc. = Specific problems (e.g., “file not found,” “command not executable,” etc.)
You don’t always see these numbers on the screen, but Linux stores the last command’s exit status in a special variable: $?. You can check it anytime to determine whether the previous command succeeded or failed.
How to Check Exit Status of a Command
In Linux, the exit status of the last command you ran is stored in a special shell variable called:
$?
Example : Successful Command
ls
echo $?
What happens here:
- First, ls lists the files in your current directory.
- Since the command completed without errors, Linux sets the exit status to 0.
- When we check the status with echo $?, it prints 0.
Example : Failed Command
ls /notexisting
echo $?
What happens here:
- We try to list files in /notexisting, which doesn’t exist.
- The ls command fails, so Linux sets a non-zero exit status (here, 2).
- If we check with echo $?, we would see:
Example : Using Exit Status in a Script
Exit statuses are especially useful in shell scripts, where decisions depend on whether a command succeeded or failed.
Here’s a simple example:
#!/bin/bash
ls /etc > /dev/null
if [ $? -eq 0 ]; then
echo "Command successful!"
else
echo "Command failed!"
fi
Common Exit Status Codes
Here are frequently seen exit codes:
| Exit Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse of shell command |
| 126 | Command found but not executable |
| 127 | Command not found |
| 130 | Script terminated by Ctrl+C |
| 255 | Exit status out of range |
Final thoughts
The exit status is a small number with a big impact, whether you’re running commands interactively or writing shell scripts. Understanding exit codes helps you debug and control your workflow.
Next time a command doesn’t work as expected, don’t rely on the error message alone—check the exit status as well.
