📘 Exit Status Codes - General Explain
🎯 What You Will Learn
- Understand the meaning and purpose of exit status codes in Bash.
- Learn how to use the special variable
$?to check command results. - Identify standard system exit codes (0–255) and their meanings.
- Implement success/failure logic using exit codes for automation reliability.
- Apply exit handling in WordPress backup, update, and monitoring scripts.
- Use
exitmanually in scripts to signal custom outcomes.
1. 5W + 1H Framework
| Element | Description |
| What | Exit status codes are numeric values returned by commands to indicate success or failure. |
| Why | They allow scripts to make decisions, retry, or stop based on whether a command succeeded or failed. |
| Who | Used by Bash, system daemons, and developers automating Linux/WordPress workflows. |
| Where | Every executed command (interactive or script) produces an exit code. |
| When | After each command or script execution, accessed immediately using $?. |
| How | 0 means success, non-zero values (1–255) mean failure or specific errors. |
2. Prerequisites
- Basic understanding of running Bash commands and scripts.
- Knowledge of command chaining (
&&,||) from Module 2.2. - Familiarity with terminal navigation and permissions.
3. Core Concept
Every command executed in Linux returns an exit status to indicate whether it succeeded or failed.
You can view the result using the $? variable immediately after execution.
ls /var/www/html
echo $?
Expected Output (if directory exists):
0
Expected Output (if directory doesn’t exist):
2
4. Standard Exit Codes Reference
| Code | Meaning | Description |
0 | Success | Command executed successfully. |
1 | General Error | Catch-all for general failures. |
2 | Misuse of Shell Builtins | Syntax or incorrect command usage. |
126 | Command Invoked Cannot Execute | Permission or execution problem. |
127 | Command Not Found | Missing or invalid command. |
128 | Invalid Exit Argument | Exit called with invalid number. |
130 | Script Terminated (Ctrl+C) | Interrupted manually. |
137 | Killed (SIGKILL) | Terminated by system or OOM (Out Of Memory). |
255 | Out of Range / Fatal Error | Typically custom fatal errors. |
5. Checking Exit Codes in Practice
5.1 Successful Command
echo "Hello, world!"
echo $?
Expected Output:
Hello, world!
0
5.2 Failed Command
ls /nonexistent/path
echo $?
Expected Output:
ls: cannot access '/nonexistent/path': No such file or directory
2
6. Using Exit Codes in Conditional Logic
wp plugin update --all --path=/var/www/html
if [ $? -eq 0 ]; then
echo "✅ Plugins updated successfully."
else
echo "❌ Plugin update failed."
fi
Expected Output (success):
✅ Plugins updated successfully.
Expected Output (failure):
❌ Plugin update failed.
7. Short Form Using Chaining
Instead of if, you can use chaining (&&, ||):
wp core update --path=/var/www/html && echo "Core update success" || echo "Core update failed"
8. Manual Exit in Scripts
You can explicitly exit a script with a custom code:
#!/bin/bash
tar -czf /home/backup/wp.tar.gz /var/www/html || { echo "Backup failed"; exit 1; }
echo "Backup completed successfully"
exit 0
Explanation:
exit 1— signals failure to parent process (cron, CI, etc.).exit 0— signals success. Expected Behavior: If backup fails, script stops immediately with exit code 1. Check script result:
echo $?
9. Integrating with Cron and Monitoring Systems
Monitoring tools and cron jobs rely on exit codes:
0→ no alert1or higher → alert, retry, or log error Example cron entry:
0 2 * * * /home/user/scripts/wp_backup.sh || echo "Backup failed on $(hostname)" >> /var/log/alerts.log
10. Multi-Step Workflow Example
#!/bin/bash
echo "Starting WordPress maintenance..."
wp plugin update --all --path=/var/www/html
code=$?
if [ $code -eq 0 ]; then
echo "Plugins updated successfully."
else
echo "Plugin update failed with code: $code"
exit $code
fi
wp theme update --all --path=/var/www/html
echo "Maintenance completed successfully."
exit 0
Expected Output (success):
Starting WordPress maintenance...
Success: Updated all plugins.
Plugins updated successfully.
Maintenance completed successfully.
If plugin update fails:
Starting WordPress maintenance...
Error: Connection timeout.
Plugin update failed with code: 1
11. Best Practices
| Practice | Description |
Always check $? after critical commands | Ensures error handling logic runs correctly. |
Use meaningful exit codes (0, 1, 2, 255) | Helps monitoring tools identify type of failure. |
Exit early on failure using set -e | Stops script immediately when a command fails. |
| Log both command and exit code | Simplifies debugging and audit trails. |
| Use chaining for concise scripts | Replace verbose if checks with && and ` |
12. Static vs Dynamic Framing
| Framing | Description | Behavior |
| Static | Hardcoded return codes | Simple but less flexible |
| Dynamic | Contextual based on $? | Adapts to runtime results, ideal for automation |
13. Troubleshooting Matrix
| Issue | Symptom | Cause | Solution |
$? always 0 | Variable checked too late | A new command executed before reading $? | Immediately check after command. |
| Script keeps running after failure | No exit or set -e used | Missing termination control | Add set -e or manual exit codes. |
| “Command not found” | Exit code 127 | Missing binary or typo | Verify with which command. |
| “Permission denied” | Exit code 126 | Script lacks execute permission | chmod +x script.sh. |
14. Quick Lab – Error-Aware Backup Script
Script: safe_backup.sh
#!/bin/bash
set -e
echo "Starting backup..."
tar -czf /home/backup/wp_backup_$(date +%F).tar.gz /var/www/html || exit 2
echo "Backup created successfully."
exit 0
Run:
chmod +x safe_backup.sh
./safe_backup.sh
echo $?
Expected Output (success):
Starting backup...
Backup created successfully.
0
Expected Output (failure):
tar: /var/www/html: No such file or directory
2
15. Cheat Sheet
| Task | Command / Example |
| Check last command status | echo $? |
| Success code | 0 |
| General failure | 1 |
| Command not found | 127 |
| Stop script on error | set -e |
| Custom exit code | exit 5 |
| Combine check + message | `cmd && echo "OK" |
| Log exit code | echo $? >> /var/log/result.log |
16. Mini-Quiz
| # | Question | Answer |
| 1 | What does exit code 0 represent? | Success |
| 2 | How do you check the last command’s exit code? | echo $? |
| 3 | What does exit code 127 mean? | Command not found |
| 4 | How can you stop a script when a command fails? | Use set -e or exit after error. |
| 5 | Why use exit codes in cron jobs? | To detect failures and trigger alerts or retries. |
Would you like me to continue next with Module 2.4 – Conditional Execution (if, elif, else) to connect this module’s exit logic into full control flow scripting?