Exploring Bash — Part 7

Dineshkumaar R
5 min readApr 12, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Let’s dive right in! Error handling is a crucial aspect of writing robust and reliable Bash scripts. Whether you’re a seasoned developer or just starting with Bash scripting, understanding how to handle errors gracefully can make your scripts more resilient and easier to maintain. In this blog, we’ll explore various techniques and best practices for error handling in Bash scripts, along with practical examples.

Understanding Exit Status

In Bash, every command executed returns an exit status, which indicates whether the command was successful or encountered an error. An exit status of 0 typically signifies success, while any non-zero value indicates an error.

# Check the exit status of a command
ls /
echo "Exit status: $?"
echo "\n"
ls /Dinesh/
echo "Exit status: $?"

Basic Error Handling with if Statements

One of the simplest ways to handle errors in Bash scripts is by using if statements to check the exit status of commands.

The script does indirectly relate to exit status. In Bash, every command or operation returns an exit status upon completion, indicating whether the operation was successful or encountered an error.

#!/bin/bash

# Example: Check if a file exists
if [ -f "file_dinesh.txt" ]; then
echo "File exists."
else
echo "File does not exist."
fi

In the script provided:
• The command [ -f “myfile.txt” ] checks if the file “myfile.txt” exists. This command returns an exit status of 0 if the file exists and 1 if it does not.
• The if statement evaluates the exit status returned by the command. If the exit status is 0 (indicating success), the script prints “File exists.” Otherwise, it prints “File does not exist.”

So, while the script does not directly use the exit command to set the exit status, it does rely on the exit status of the [ -f “myfile.txt” ] command to determine the flow of execution.

Handling Specific Errors

Sometimes, you may want to handle specific errors differently. You can achieve this by checking the error message or exit status of commands.

#!/bin/bash

# Example: Handling file not found error
if [ ! -f "myfile.txt" ]; then
echo "File not found. Exiting."
exit 1
fi

Utilizing ‘trap’ for Cleanup and Error Handling

The trap command in Bash enables executing commands upon receiving specific signals, such as errors or interruptions, facilitating cleanup tasks or error logging.

#!/bin/bash

# Example: Trap signals for cleanup
cleanup() {
echo "Cleanup function is being executed."
# Perform cleanup tasks here, such as removing temporary files or releasing resources
}

# Set up trap to call cleanup function on EXIT
trap 'cleanup; echo "Trap signal received."' EXIT

# Main script logic
echo "Script started."

# Simulate some work
sleep 5

# Introduce an error
echo "Triggering an error..."
cat dinesh.txt

# This line won't be executed if an error occurs before it
echo "Script completed successfully."

• The script defines a cleanup function responsible for executing tasks like removing temporary files or releasing resources.
• It sets up a trap using the trap command to ensure that the cleanup function is called when the script exits, indicated by the EXIT signal.
• Upon starting, the script prints “Script started.” to indicate its execution initiation.
• It simulates work using the sleep command to pause execution for 5 seconds.
• The script intentionally introduces an error by attempting to read from a file (dinesh.txt) using the cat command.
• Regardless of whether the script encounters an error or completes successfully, the cleanup function is invoked due to the trap, ensuring proper cleanup tasks are performed before the script exits.
• The script prints “Cleanup function is being executed.” to indicate the cleanup process, followed by “Trap signal received.” to signify the trap signal execution.
• If no error occurs, the script prints “Script completed successfully.” before exiting.

Logging Errors

Logging errors can be immensely helpful for troubleshooting and debugging your scripts. You can redirect error messages to a log file using standard output and standard error redirection.

#!/bin/bash

# Example: Redirect errors to a log file
exec >> error.log 2>&1

# Main script logic
ls dinesh #dinesh is a file name or directory

Summary of the blog

1. Bash commands return exit status indicating success (0) or error (non-zero).
2. Utilize if statements to handle errors by evaluating command exit statuses.
3. Strategies exist for treating specific errors differently based on error messages or exit statuses.
4. ‘Trap’ command executes tasks upon receiving specific signals like errors or interruptions.
5. Importance stressed on error logging for troubleshooting and debugging scripts.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17
  4. Exploring bash — Part4 : https://medium.com/@dineshkumaar478/exploring-bash-part-4-4521aaac30ea
  5. Exploring bash — Part5 : https://medium.com/@dineshkumaar478/exploring-bash-part-5-a136eb036b4f
  6. Exploring bash — Part6 : https://medium.com/@dineshkumaar478/exploring-bash-part-6-31887f5c3695

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)