Handling Script Failures in Bash (original) (raw)

Last Updated : 22 Apr, 2026

Bash scripts often perform multiple system tasks and errors are inevitable. Proper error handling ensures that your scripts exit gracefully and provide meaningful feedback to users, preventing unexpected behaviour or system issues.

Understanding Exit Codes

Exit codes indicate the result of a command or script execution in Bash.

Scripts can check exit codes to determine if a command succeeded and act accordingly.

Example: Checking Exit Status

**Script:

#!/bin/bash
mkdir /tmp/example
echo $?

status-script

**Output (Successful Case):

status-script-op

**Output (Failure Case):

status-script-fail-op

Techniques for Error Handling in Bash

1. Using the exit Command and Exit Codes

The exit command is the most direct way to stop a Bash script when an error occurs. It terminates the script immediately and returns a numeric exit status to the shell.

**Example: Exit When a Command Fails

Stop the script if directory creation fails.

**Script:

#!/bin/bash
mkdir /tmp/example

if [ $? -ne 0 ]; then
exit 1
fi

mkdir-script

**Output (Failure Case):

mkdir-script-op

**Example with Error Message:

Provide user-friendly feedback before exiting.

**Script:

#!/bin/bash
mkdir /root/protected_dir

if [ $? -ne 0 ]; then
echo "Error: Failed to create directory"
exit 1
fi

eror-mkdir-script

**Output:

eror-mkdir-script-op

2. Using set -e to Exit Automatically on Errors

The set -e option instructs Bash to exit the script immediately if any command returns a non-zero exit status. This removes the need to manually check $? after every command.

**Note: set -e applies to the entire script. If a command fails inside a function or subshell, the script will also exit.

**Example: Immediate Exit on Failure

Stop execution as soon as a command fails.

**Script:

#!/bin/bash
set -e

ls /nonexistent_directory
echo "This line will not be executed"

set-e-script

**Output:

set-e-script-op

3. Using trap Command for Cleanup and Error Handling

The trap command allows you to specify commands to be executed when a script exits, regardless of whether it exits successfully or due to an error. This is particularly useful for cleanup tasks like removing temporary files or undoing operations.

**Example: Cleanup on Exit

Remove a temporary directory when the script exits.

**Script:

#!/bin/bash
trap 'rm -rf /tmp/example' EXIT

mkdir /tmp/example

other script operations

exit 0

trap-script

**Output:

trap-script-o

4. Command Substitution for Error Handling

Command substitution allows you to capture the output of a command and store it in a variable. This is useful when you want to display meaningful error messages or process command results before deciding whether to exit the script.

**Example: Capture Output and Check Failure

Store the result of a command and exit if it fails.

**Script:

#!/bin/bash
result=$(mkdir /root/protected_dir 2>&1)

if [ $? -ne 0 ]; then
echo "Error: $result"
exit 1
fi

cmnd-sub-sc

**Output (Failure Case):

cmnd-sub-sc-op

In this example, if the mkdir command fails to create the directory, the error message will be assigned to the "result" variable and displayed on the console.

5. Suppressing Error Messages

In some cases, a command may fail but the error message is not important for the user. Bash allows you to suppress error output while still checking whether the command succeeded or failed.

**Example: Suppress Standard Error

Hide error messages but exit if the command fails.

**Script:

#!/bin/bash
mkdir /root/protected_dir 2> /dev/null

if [ $? -ne 0 ]; then
exit 1
fi

sup-std-srcpt

**Output:

sup-std-srcpt-op

6. Exit When Any Command Fails

Sometimes, you want a script to stop immediately if any command fails, not just specific ones. Bash provides multiple ways to achieve this, including set -e, the || operator and manual exit status checks.

**Using || exit 1:

Exit only if a specific command fails.

**Script:

#!/bin/bash
ls /nonexistent_directory || exit 1
echo "This line will not be executed"

selective-script

**Output:

selective-script-op

**Using $? with an if Condition

Check the last command’s exit status and decide whether to exit.

**Script:

#!/bin/bash
ls /nonexistent_directory

if [ $? -ne 0 ]; then
echo "Command failed"
exit 1
else
echo "Command succeeded"
fi

ex6-2-script

**Output:

ex6-2-op

**Important Notes:

set +e

commands that may fail

set -e

7. Exit Only When Specific Commands Fail

In some cases, you might not want to stop the entire script if just one command fails. Instead, you can choose to exit only when specific commands fail, allowing other commands to continue executing.

**Using || exit 1 for Specific Commands

Stop the script when a particular (critical) command fails, but continue executing other non-critical commands.

**Script:

#!/bin/bash

Non-critical command (allowed to fail)

rm /nonexistent_file || true
echo "Script continues after rm failure"

Critical command (must succeed)

ls /nonexistent_directory || exit 1
echo "This line will NOT run if ls fails"

ex7-1-script

**Output:

ex7-1-op

**Using $? to Check Exit Status

Manually check whether a command succeeded or failed before deciding to exit.

**Script:

#!/bin/bash
ls /nonexistent_directory

if [ $? -ne 0 ]; then
echo "Command failed"
exit 1
else
echo "Command succeeded"
fi

echo "This line will be executed"
rm /nonexistent_file
if [ $? -ne 0 ]; then
echo "Command failed"
else
echo "Command succeeded"
fi

ex7-2-script

**Output:

ex7-2-op

Practical Tips for Handling Script Failures

Handling errors effectively in Bash scripts ensures reliability, readability and easier maintenance. Here are some best practices and tips: