Skip to main content

Command Palette

Search for a command to run...

Error Handling in Shell Scripting

Updated
Error Handling in Shell Scripting
R

Rajat Chauhan is a skilled Devops Engineer, having experience in automating, configuring, deploying releasing and monitoring the applications on cloud environment.

• Good experience in areas of DevOps, CI/CD Pipeline, Build and Release management, Hashicorp Terraform, Containerization, AWS, and Linux/Unix Administration. • As a DevOps Engineer, my objective is to strengthen the company’s applications and system features, configure servers and maintain networks to reinforce the company’s technical performance. • Ensure that environment is performing at its optimum level, manage system backups and provide infrastructure support. • Experience working on various DevOps technologies/ tools like GIT, GitHub Actions, Gitlab, Terraform, Ansible, Docker, Kubernetes, Helm, Jenkins, Prometheus and Grafana, and AWS EKS, DevOps, Jenkins. • Positive attitude, strong work ethic, and ability to work in a highly collaborative team environment. • Self-starter, Fast learner, and a Team player with strong interpersonal skills • Developed shell scripts (Bash) for automating day-to-day maintenance tasks on top of that have good python scripting skills. • Proficient in communication and project management with good experience in resolving issues.

Understanding how to handle errors in shell scripts is crucial for creating robust and reliable scripts. Today, you'll learn how to use various techniques to handle errors effectively in your bash scripts.

Topics to Cover

  1. Understanding Exit Status: Every command returns an exit status (0 for success and non-zero for failure). Learn how to check and use exit statuses.

  2. Using if Statements for Error Checking: Learn how to use if statements to handle errors.

  3. Using trap for Cleanup: Understand how to use the trap command to handle unexpected errors and perform cleanup.

  4. Redirecting Errors: Learn how to redirect errors to a file or /dev/null.

  5. Creating Custom Error Messages: Understand how to create meaningful error messages for debugging and user information.

Tasks

Task 1: Checking Exit Status

Write a script that attempts to create a directory and checks if the command was successful. If not, print an error message.

#!/bin/bash

my_directory=$1

mkdir $1

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

Task 2: Using if Statements for Error Checking

Modify the script from Task 1 to include more commands (e.g., creating a file inside the directory) and use if statements to handle errors at each step.

#!/bin/bash
my_directory=$1
my_file=$2

mkdir $1

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

echo "Directory "$1" created successfully."

touch "$1"/"$2"

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

echo "File "$1" created successfully in "$1"."

Task 3: Using trap for Cleanup

Write a script that creates a temporary file and sets a trap to delete the file if the script exits unexpectedly.

#!/bin/bash

temp_file=$(mktemp)

trap "rm -f $temp_file; echo 'Temporary file deleted.'" EXIT

echo "Temporary file created at $temp_file."

# Simulate some work
sleep 5

# Simulate unexpected exit
exit 1

Task 4: Redirecting Errors

Write a script that tries to read a non-existent file and redirects the error message to a file called error.log.

#!/bin/bash

cat non_existent_file.txt 2> error.log

if [ $? -ne 0 ]; then
  echo "Error: Failed to read 'non_existent_file.txt'. Check 'error.log' for details."
fi

Task 5: Creating Custom Error Messages

Modify one of the previous scripts to include custom error messages that provide more context about what went wrong.

#!/bin/bash
my_directory=$1
my_file=$2

mkdir $1

if [ $? -ne 0 ]; then
  echo "Error: Failed to create directory "$1". Please check if the directory already exists or if you have the necessary permissions."
  exit 1
fi

echo "Directory "$1" created successfully."

touch "$1"/"$2"

if [ $? -ne 0 ]; then
  echo "Error: Failed to create file '$2' inside "$1". Ensure you have write permissions in the directory."
  exit 1
fi

echo "File "$2" created successfully in "$1"."

These tasks and examples will help you understand how to effectively handle errors in your bash scripts, making them more robust and reliable.

Shell Scripting

Part 4 of 4

A shell script is a computer program designed to be run by a Linux shell, a command-line interpreter. Typical operations performed by shell scripts include file manipulation, program execution, and printing text.

Start from the beginning

Shell Scripting Challenge

Shell scripting in Bash is an essential skill for any Linux user, especially for DevOps professionals. It allows for automating tasks, managing systems efficiently, and performing repetitive tasks with ease. In this guide, we will walk through some f...

More from this blog

R

Rajat Chauhan

63 posts