
What Are Exit Codes?
Every command in Bash returns an exit code (also called a return status).
You can check the exit status of the last command using the special variable:
$$
echo $?
$$
For example:
$$
ls /etc
echo $? # Likely prints 0 (success)
ls /nonexistent_folder
echo $? # Prints non-zero, e.g., 2 (failure)
$$
Common Exit Codes in Bash
Some commands use standard exit codes:
0 → Command succeeded
1 → General error
2 → Misuse of shell built-ins (syntax error, etc.)
126 → Command found but not executable
127 → Command not found
130 → Script terminated by Ctrl+C
137 → Process killed (e.g., kill -9
)
📌 Pro Tip: Not all programs follow these standards, but many Unix tools do.
Checking Exit Codes with if
You can run commands and check if they succeed:
$$
if ls /etc > /dev/null; then
echo “Directory exists!”
else
echo “Directory not found!”
fi
$$
This script prints “Directory exists!” if /etc
is present, otherwise it prints the error message.
Using &&
and ||
for Quick Error Handling
Instead of if
, you can chain commands:
Example:
$$
mkdir mydir && echo “Directory created successfully”
mkdir mydir || echo “Failed to create directory”
$$
Forcing Scripts to Exit on Error
By default, a script keeps running even if a command fails. To stop immediately:
$$
set -e
$$
Example:
$$
#!/bin/bash
set -e
cp file1.txt /tmp/
cp file2.txt /tmp/
echo “All files copied successfully!”
$$
If file1.txt
doesn’t exist, the script stops right there instead of continuing.
👉 Combine with set -u
(treat unset variables as errors) and set -o pipefail
(catch errors in pipelines) for safer scripting:
$$
set -euo pipefail
$$
Error Handling with trap
Sometimes, you want to clean up resources before exiting (like removing temporary files). That’s where trap
comes in.
$$
#!/bin/bash
trap ‘echo “Error occurred. Cleaning up…”; rm -f /tmp/tempfile’ ERR
cp /nonexistent/file /tmp/tempfile
echo “This will not run if error happens.”
$$
If the cp
fails, the trap is triggered, printing the message and cleaning up.
Custom Exit Codes
You can control what exit code your script returns using exit
:
$$
#!/bin/bash
if [ ! -f “important.txt” ]; then
echo “File missing!”
exit 2
fi
echo “File found!”
exit 0
$$
Here, the script exits with 2 if the file is missing, and 0 if successful.
Real-World Use Cases of Error Handling
Automation Scripts
- Stop backups immediately if the disk is full.
- Exit with meaningful codes for monitoring tools like Nagios or Zabbix.
Deployment Pipelines
System Administration
Data Processing
Common Mistakes in Error Handling
❌ Forgetting to check $?
→ Scripts assume success and fail silently.
❌ Using set -e
blindly → Sometimes you need more granular handling.
❌ Not logging errors → Hard to debug what went wrong.
❌ Using vague exit codes → Always use meaningful custom codes where possible.