Skip to main content

📘 Exit Status Codes - General Explain


🎯 What You Will Learn

  1. Understand the meaning and purpose of exit status codes in Bash.
  2. Learn how to use the special variable $? to check command results.
  3. Identify standard system exit codes (0–255) and their meanings.
  4. Implement success/failure logic using exit codes for automation reliability.
  5. Apply exit handling in WordPress backup, update, and monitoring scripts.
  6. Use exit manually in scripts to signal custom outcomes.

1. 5W + 1H Framework

ElementDescription
WhatExit status codes are numeric values returned by commands to indicate success or failure.
WhyThey allow scripts to make decisions, retry, or stop based on whether a command succeeded or failed.
WhoUsed by Bash, system daemons, and developers automating Linux/WordPress workflows.
WhereEvery executed command (interactive or script) produces an exit code.
WhenAfter each command or script execution, accessed immediately using $?.
How0 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

CodeMeaningDescription
0SuccessCommand executed successfully.
1General ErrorCatch-all for general failures.
2Misuse of Shell BuiltinsSyntax or incorrect command usage.
126Command Invoked Cannot ExecutePermission or execution problem.
127Command Not FoundMissing or invalid command.
128Invalid Exit ArgumentExit called with invalid number.
130Script Terminated (Ctrl+C)Interrupted manually.
137Killed (SIGKILL)Terminated by system or OOM (Out Of Memory).
255Out of Range / Fatal ErrorTypically 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 alert
  • 1 or 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

PracticeDescription
Always check $? after critical commandsEnsures 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 -eStops script immediately when a command fails.
Log both command and exit codeSimplifies debugging and audit trails.
Use chaining for concise scriptsReplace verbose if checks with && and `

12. Static vs Dynamic Framing

FramingDescriptionBehavior
StaticHardcoded return codesSimple but less flexible
DynamicContextual based on $?Adapts to runtime results, ideal for automation

13. Troubleshooting Matrix

IssueSymptomCauseSolution
$? always 0Variable checked too lateA new command executed before reading $?Immediately check after command.
Script keeps running after failureNo exit or set -e usedMissing termination controlAdd set -e or manual exit codes.
“Command not found”Exit code 127Missing binary or typoVerify with which command.
“Permission denied”Exit code 126Script lacks execute permissionchmod +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

TaskCommand / Example
Check last command statusecho $?
Success code0
General failure1
Command not found127
Stop script on errorset -e
Custom exit codeexit 5
Combine check + message`cmd && echo "OK"
Log exit codeecho $? >> /var/log/result.log

16. Mini-Quiz

#QuestionAnswer
1What does exit code 0 represent?Success
2How do you check the last command’s exit code?echo $?
3What does exit code 127 mean?Command not found
4How can you stop a script when a command fails?Use set -e or exit after error.
5Why 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?