Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Shell Scripting
  • Kali Linux
  • Ubuntu
  • Red Hat
  • CentOS
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Python
  • R
  • Java
  • C
  • C++
  • JavaScript
  • DSA
Open In App
Next Article:
How to Exit When Errors Occur in Bash Scripts
Next article icon

How to Exit When Errors Occur in Bash Scripts

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Exit codes
 

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:

Exit Codes
 

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:

Using -e option
 

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:

Using trap command
 

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:

Command Substitution
 

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:

Suppressing Error Messages
 

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:

Exiting when command fails
 

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:

Exiting when command fails
 

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:

Exiting when command fails
 

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:

Exiting when specific command fails
 

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:

Exiting when specific command fails

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.


Next Article
How to Exit When Errors Occur in Bash Scripts

L

lucifer2411
Improve
Article Tags :
  • Linux-Unix
  • How To
  • Bash-Script

Similar Reads

    How To Run Bash Script In Linux?
    Bash scripts, also called shell scripts, are programs that help automate tasks by storing a series of commands that often go together, like updates or upgrades. These scripts make it easier to perform tasks automatically instead of typing each command manually. After creating a Bash script, you can
    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 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
    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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences