Skip to main content

πŸ“˜ Exit Status Code = 1 in Bash



🎯 What You Will Learn​

  1. Understand what exit status code = 1 means in Bash.
  2. Learn how it differs from other exit codes like 0, 2, or 127.
  3. Identify common causes and real-world scenarios where exit code 1 occurs.
  4. Learn to use $? to check exit status in scripts.
  5. Handle failures and automate reactions using conditional statements.
  6. Apply knowledge to WordPress VPS management, such as failed commands or permission errors.

1. 5W + 1H Framework​

ElementDescription
WhatExit status code 1 indicates a general error in Bash β€” meaning something went wrong, but not specific enough for a distinct code (like 2, 126, 127, etc.).
WhyIt helps scripts detect when a command fails due to syntax error, file not found, wrong arguments, or runtime error.
WhoUseful for system admins, DevOps engineers, and developers writing Bash scripts.
WhenWhen a command or script exits unsuccessfully (not completed as expected).
WhereIn any Linux terminal, Bash automation, or VPS script execution.
HowBy checking the special variable $? after a command to see if it returns 1, then handle accordingly.

2. Prerequisites​

Before you start, make sure you:

  • Understand exit codes conceptually (0 = success, non-zero = failure).
  • Know how to execute simple Bash commands.
  • Know how to view exit code with $?.
  • Have access to a Linux terminal or VPS environment.

3. Core Syntax and Examples​

🧩 Basic Concept​

command
echo $?

If the command executes successfully β†’ Output is 0. If it fails β†’ Output might be 1 (general error) or another specific code.​

Example 1 – Missing File​

cat non_existing_file.txt
echo $?

Expected Output:

cat: non_existing_file.txt: No such file or directory
1

Explanation: The cat command failed because the file doesn’t exist. Bash returns 1 as a general error code. Use Case (WordPress VPS): Running cat /var/www/html/wp-config.php when file path is mistyped or missing.​

Example 2 – Invalid Argument​

ls --invalidoption
echo $?

Expected Output:

ls: unrecognized option '--invalidoption'
Try 'ls --help' for more information.
1

Explanation: The ls command doesn’t recognize the flag. Bash exits with status 1. Use Case (WordPress VPS): When running wp plugin update --unknowflag, it will fail with exit code 1.​

Example 3 – Script Returning Exit 1​

#!/bin/bash
echo "Testing failure condition"
exit 1

Run it:

bash test_script.sh
echo $?

Expected Output:

Testing failure condition
1

Explanation: Script explicitly returns exit code 1 to indicate a general failure. Use Case: Used in Bash automation for health checks (e.g., PHP restart failed).​

Example 4 – Condition Check in Script​

#!/bin/bash
ping -c 1 nonexistentsite.com &>/dev/null
if [ $? -eq 1 ]; then
echo "Ping failed. Network or DNS issue detected."
fi

Expected Output:

Ping failed. Network or DNS issue detected.

Explanation: The ping command failed and returned exit code 1. The script handles it with an if condition.​

Example 5 – Combining with && or ||​

mkdir /restricted && echo "Directory created" || echo "Failed with exit code $?"

Expected Output:

mkdir: cannot create directory β€˜/restricted’: Permission denied
Failed with exit code 1

Explanation: The first command failed due to lack of permission, triggering the second one with error 1. Use Case (WordPress VPS): When trying to write to /etc/ or /root/ without sudo.​

4. Common Scenarios That Trigger Exit Code 1​

ScenarioExample CommandDescription
File not foundcat missing.txtNon-existent file path
Wrong argumentls --wrongInvalid command-line flag
Permission deniedmkdir /root/testRequires sudo privileges
Runtime failuregrep "text" folder/Directory given instead of file
WP-CLI errorwp plugin install plugin.zip (corrupted zip)Fails extraction

5. Practical WordPress VPS Use Cases​

Use CaseExampleExplanation
Plugin update failedwp plugin update allExit code 1 indicates error (e.g., timeout or file permission)
Backup script checktar -czf backup.tar.gz /var/www/htmlIf compression fails, return 1
Service restart checksystemctl restart mysqlIf MySQL not running, code 1
Deployment taskrsync /src /destMissing directory or permission issue triggers 1

6. Troubleshooting Matrix​

SymptomPossible CauseFix
Exit code = 1 after running commandCommand syntax errorDouble-check command or flags
File or directory not foundWrong pathVerify path using ls
Permission deniedRunning as non-rootUse sudo
Script fails silentlyNo error outputAdd set -e to stop on first failure

7. Best Practices​

  1. Always check exit code using $? after critical commands.
  2. Use set -e in scripts to abort automatically on error 1.
  3. Combine with logging:
command || echo "$(date): command failed with exit code $?" >> /var/log/script.log

  1. Use trap to handle unexpected exit 1 gracefully.
  2. In production VPS, prefer meaningful return codes (e.g., exit 2, exit 3) for debugging clarity.

8. Quick Lab – Detecting Exit Code 1​

Step 1: Create a test script​

nano /root/exit1_test.sh

Step 2: Insert​

#!/bin/bash
echo "Checking file..."
cat /tmp/no_file_here.txt
echo "Exit code is $?"

Step 3: Run​

bash /root/exit1_test.sh

Expected Output:​

Checking file...
cat: /tmp/no_file_here.txt: No such file or directory
Exit code is 1


9. Cheat Sheet​

CodeMeaningDescription
0SuccessCommand executed successfully
1General errorNon-specific failure (most common)
2Misuse of shell builtinsSyntax or invalid option
126Cannot executePermission or non-executable
127Command not foundBinary or path missing
130TerminatedUser stopped process (Ctrl+C)

10. Mini-Quiz​

  1. What does exit code 1 generally mean in Bash?
  2. What is the output of $? if a command succeeds?
  3. In a VPS script, how can you trigger exit code 1 manually?
  4. What happens if you run mkdir /root/test as a non-root user?
  5. How can you automatically stop a script when any command returns exit 1?

Would you like me to continue this series next with Exit Status Code = 2 (Misuse of Shell Builtins) in the same standardized format?