codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐧

Linux & Bash

48 / 60 topics
39Advanced Scripting40Bash Arrays41Bash Associative Arrays42Advanced Functions43Advanced Script Debugging44Script Optimization45Automation with Scripts46Script Integration47Script Logging48Error Handling49Script Performance50Parallel Processing51Remote Execution52Configuration Management53Script Monitoring54Automation Tools55Continuous Integration56Script Deployment57Script Security58Script Audit59Optimization Tips60Advanced Debugging
Tutorials/Linux & Bash/Error Handling
🐧Linux & Bash

Error Handling

Updated 2026-05-15
10 min read

Error Handling

Introduction

In the world of scripting, error handling is a crucial aspect that ensures your scripts are robust and can gracefully handle unexpected situations. Bash, being one of the most widely used scripting languages, provides several mechanisms to handle errors effectively. This tutorial will guide you through understanding how to manage errors in Bash scripts, ensuring they behave predictably even when faced with issues.

Concept

Error Codes

Every command executed in a Bash script returns an exit status, which is a number between 0 and 255. The value 0 typically indicates success, while any other value signifies an error or failure. Understanding how to capture and respond to these exit statuses is fundamental to effective error handling.

Conditional Execution

Bash provides conditional execution operators that allow you to execute commands based on the exit status of previous commands. These include:

  • &&: Executes the next command only if the previous one succeeded (exit status 0).
  • ||: Executes the next command only if the previous one failed (non-zero exit status).

Error Trapping

Bash allows you to trap signals and errors using the trap command, enabling you to define custom actions when specific events occur. This is particularly useful for cleaning up resources or logging error information.

Examples

Basic Error Checking

Let's start with a simple example where we check if a file exists before attempting to read it:

Bash
1#!/bin/bash
2
3# Check if the file exists
4if [[ -f "example.txt" ]]; then
5 echo "File exists, proceeding..."
6else
7 echo "File does not exist!"
8 exit 1
9fi

In this script, we use the -f flag to check if example.txt is a regular file. If it doesn't exist, the script prints an error message and exits with a status of 1.

Using Conditional Execution

Here's how you can use conditional execution to handle errors:

Bash
1#!/bin/bash
2
3# Attempt to create a directory
4mkdir new_directory && echo "Directory created successfully!" || echo "Failed to create directory!"

In this example, mkdir is executed first. If it succeeds (returns 0), the message "Directory created successfully!" is printed. Otherwise, the error message "Failed to create directory!" is displayed.

Error Trapping

Let's see how you can use trap to handle errors and perform cleanup:

Bash
1#!/bin/bash
2
3# Function to clean up
4cleanup() {
5 echo "Cleaning up..."
6 rm -f temp_file.txt
7}
8
9# Trap the EXIT signal
10trap cleanup EXIT
11
12# Create a temporary file
13touch temp_file.txt
14
15# Simulate an error
16false && exit 1 || echo "An error occurred!"
17
18# The script will still clean up even if an error occurs

In this script, we define a cleanup function that removes temp_file.txt. We then use trap to call this function when the script exits, regardless of whether it succeeds or fails. This ensures that resources are always cleaned up properly.

Handling Specific Exit Codes

Sometimes, you might want to handle specific exit codes differently:

Bash
1#!/bin/bash
2
3# Function to handle errors
4handle_error() {
5 case $? in
6 1) echo "General error occurred." ;;
7 2) echo "File not found." ;;
8 *) echo "Unknown error." ;;
9 esac
10}
11
12# Simulate a command that returns a specific exit code
13ls non_existent_file 2>/dev/null || handle_error

In this example, ls is used to list a file that doesn't exist. The handle_error function checks the exit status ($?) and prints an appropriate message based on the code.

What's Next?

Now that you have a good understanding of error handling in Bash scripts, you might want to explore how to enhance script performance by optimizing commands and managing resources efficiently. This will help you write more efficient and reliable scripts.

By mastering these techniques, you'll be well-equipped to handle errors effectively and ensure your Bash scripts run smoothly under various conditions.


PreviousScript LoggingNext Script Performance

Recommended Gear

Script LoggingScript Performance