How to Exit When Errors Occur in Bash Scripts
Last Updated :
28 Aug, 2024
When writing Bash scripts, it’s essential to include error handling to ensure that the script exits gracefully in the event of an error. In this article, we’ll cover all the possible techniques for exiting when errors occur in Bash scripts, including the use of exit codes, the “set -e” option, the “trap” command, and command substitution.
Here, we will discuss the various techniques and methods to handle errors and exit gracefully in Bash scripts.
Introduction
Error handling is an essential aspect of writing scripts, as it helps to ensure that the script exits appropriately, even when an error occurs. Without proper error handling, a script might continue to execute even when an error has occurred, leading to unexpected results or even system crashes.
Exiting when errors occur in Bash scripts is an important aspect of script development, as it helps to ensure that the script stops running and exits cleanly in the event of an error. There are several ways to exit a Bash script when an error occurs, including using the exit command, using the return command, and using the trap command. It is also important to include error handling and error messages in your script to provide useful information to the user in the event of an error.
Understanding Exit Codes
Exit codes are used to indicate the status of the script’s execution. In Bash, exit codes range from 0 to 255:
- 0: Indicates success.
- 1-255: Indicates an error or specific conditions.
Techniques for Error Handling in Bash
1. Using the ‘exit’ Command and Exit Codes
One of the simplest ways to exit a Bash script when an error occurs is to use the “exit” command with a non-zero exit code. For example, the following script exits with a code of 1 if the “mkdir” command fails.
Script:
#!/bin/bash
mkdir /tmp/example
if [ $? -ne 0 ]; then
exit 1
fi
Output:

Â
Another way to check the exit code of a command is by using the $? variable. For example, the following script also exits with a code of 1 if the “mkdir” command fails:
Script:
#!/bin/bash
mkdir /home/lucifer/yash/first
if [ $? -ne 0 ]; thenÂ
echo "Error: Failed to create directory"Â
exit 1
fi
Output:

Â
2. The ‘set -e’ Option
Another way to exit a Bash script when an error occurs is to use the “set -e” option. This option causes the script to exit immediately if any command exits with a non-zero exit code. For example, the following script exits immediately if the “mkdir” command fails:
Script:
#!/bin/bash
set -e
mkdir /tmp/example
Output:

Â
3. Leveraging the ‘trap’ Command
The ‘trap’ command allows you to specify a command or set of commands to be executed when the script exits, whether it’s due to an error or not.
#!/bin/bash
trap 'rm -rf /tmp/example' EXIT
mkdir /tmp/example
# some commands here
exit 0
Output:

Â
Here, the ‘trap’ command ensures that the /tmp/example directory is removed when the script exits, regardless of whether the exit was successful or due to an error.
4. Command Substitution for Error Handling
Another way to handle errors in Bash scripts is by using command substitution. This technique allows you to capture the output of a command and assign it to a variable. For example, the following script captures the output of the “mkdir” command and assigns it to the “result” variable. If the command fails, the script exits with a code of 1:
Script:
#!/bin/bash
result=$(mkdir /tmp/example)
if [ $? -ne 0 ]; then
echo "Error: $result"
exit 1
fi
Output:

Â
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
It is also possible to suppress the error message generated by a command by adding ‘2> /dev/null‘ to the command.
Script:
#!/bin/bash
mkdir /tmp/example 2> /dev/null
if [ $? -ne 0 ]; then
exit 1
fi
Output:

Â
In this example, if the mkdir command fails to create the directory, the error message will not be displayed on the console.
6. Exit When Any Command Fails
One way to exit a Bash script when any command fails is to use the ‘set -e’ option. This option causes the script to exit immediately if any command returns a non-zero exit status.
For example, the following script will exit if the ls command fails to list the contents of the specified directory:
Script:
#!/bin/bash
set -e
ls /nonexistent_directory
echo "This line will not be executed"
If the directory ‘/nonexistent_directory’ does not exist, the script will exit with an error message like this:
Output:

Â
And it will not execute the second line.
Another way to exit if any command fails is to use the ‘||‘ operator after each command, for example:
Script:
#!/bin/bash
ls /nonexistent_directory || exit 1
echo "This line will not be executed"This script will also exit with an error message
Output:

Â
And it will not execute the second line.
You can also check the exit status of the last command with $? variable and use the if condition with the exit command to exit if any command fails.
Script:
#!/bin/bash
ls /nonexistent_directory
if [ $? -ne 0 ]
then
echo "Command failed"
exit 1
else
echo "Command Successful"
fi
This script will also exit with an error message:
Output:

Â
And it will not execute the second line.
Note: When using the ‘set -e’ option or ‘||’ operator, the script will exit even if the failure is in a command inside a function or a subshell. To prevent this behavior, you can use ‘set +e’ before the function or subshell and ‘set -e’ after it.
7. Exit Only When Specific Commands Fail
To exit a Bash script only when specific commands fail, you can use the ‘||’ operator in conjunction with the exit command. The ‘||’ operator is used to execute a command only if the preceding command fails (returns a non-zero exit status).
For example, the following script will exit if the ls command fails to list the contents of the specified directory, but will continue to execute subsequent commands even if they fail:
Script:
#!/bin/bash
ls /nonexistent_directory || exit 1
echo "This line will be executed"
rm /nonexistent_file || true
echo "This line will also be executed"
If the directory ‘/nonexistent_directory‘ does not exist, the script will exit with an error message like this:
Output:

Â
And it will not execute the second and third lines.
Note: The true command is used to prevent the rm command from causing the script to exit if it fails. Without the true command, the script would exit if the file ‘/nonexistent_file‘ does not exist.
Another way to achieve this is by using an if statement and checking the exit status of the command with ‘$?’ variable, like:
Script:
#!/bin/bash
ls /nonexistent_directory
if [ $? -ne 0 ]
then
echo "Command failed"
exit 1
else
echo "Command Successful"
fi
echo "This line will be executed"
rm /nonexistent_file
if [ $? -ne 0 ]
then
echo "Command failed"
else
echo "Command Successful"
fi
This script will also exit with an error message:
Output:
And it will not execute the second and third lines.
Note: The exit status of the last executed command is stored in the ‘$?’ variable. And you can use it to check if the command is successful or not.
Conclusion
There are multiple ways to handle errors and exit gracefully in Bash scripts. By using exit codes, the “set -e” option, the “trap” command, command substitution, and suppressing error messages, you can ensure that your script exits in an appropriate manner and provides appropriate error handling for your script.
It’s essential to test your script with different inputs and error conditions to ensure that it is handling errors as expected. It’s also important to include clear and descriptive error messages that indicate the cause of the error and provide guidance on how to resolve it. With these techniques, you can write robust and reliable Bash scripts that can handle errors and exit gracefully.
Similar Reads
How To Run Bash Script In Linux?
Bash scripts, also known as shell scripts, are powerful tools in the world of command-line automation. They allow you to perform a series of tasks or execute commands by writing scripts that can be run in a terminal or command-line interface. However, the question often arises: how do you run a Bash
6 min read
How to Exit a Python script?
In this article, we are going to see How to Exit Python Script. Exiting a Python script refers to the termination of an active Python process. In this article, we will take a look at exiting a Python program, performing a task before exiting the program, and exiting the program while displaying a cu
4 min read
How to Create a Shell Script in linux
Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script. Shell scripts are very useful if you need to do a task routinely, like taking a backup
7 min read
How to retrieve error message using Exception class in PHP when error occurred ?
Exception handling is the important part of PHP in which we deal with how to maintain the flow of the program if there is an error or exception that occurs during the compilation. As you know we can handle the exception by throw, try-catch, die method so now we understand how to retrieve the error m
2 min read
How to Redirect Standard (stderr) Error in Bash
Bash (Bourne Again SHell) is the scripting language that is generally used to automate tasks. It is a Linux shell and command language written by Brain Fox. Bash is the default shell for Linux and macOS operating systems. What is a Standard Error in Bash?When a code is run in Bash shell and if the c
7 min read
Bash Scripting - How to check If variable is Set
In BASH, we have the ability to check if a variable is set or not. We can use a couple of arguments in the conditional statements to check whether the variable has a value. Â In this article, we will see how to check if the variable has a set/empty value using certain options like -z, -v, and -n. Usi
10 min read
Address Errors in 'if' Statements in R
Error handling is super important when writing code, no matter which language are using even in R Programming Language. Errors can happen for all sorts of reasons, like when a user gives the computer the wrong kind of information, something happens that the user didn't expect, or the user just makes
4 min read
How to terminate execution of a script in PHP ?
In this article, we are going to discuss how to terminate the execution of a PHP script. In PHP, a coder can terminate the execution of a script by specifying a method/function called the exit() method in a script. Even if the exit() function is called, the shutdown functions and object destructors
2 min read
How to Run a Shell Script in Linux
Shell scripts are a powerful way to automate tasks and manage system processes in Linux. These scripts, written in shell programming languages like Bash, allow users to execute a sequence of commands efficiently. In this guide, we'll show the steps to check a shell script in Linux before running it,
4 min read
How to Check the Syntax of a Bash Script Without Running It?
A bash script is a text file that contains a sequence of commands that are executed by the bash shell, a Unix-based command-line interface. Bash scripts are used to automate tasks, create utility scripts, and perform a wide range of other functions in the command-line environment. They can include v
5 min read