Error Handling in Shell Scripting

Error Handling in Shell Scripting

When writing shell scripts, errors can happen. Sometimes a file is missing, or a command fails. In this blog, we’ll explore basic techniques for handling errors in shell scripting with clear examples. This way, you can learn how to tackle these issues effectively!

Why is Error Handling Important?

Error handling is essential because a small mistake can stop an entire script. By knowing how to manage errors, you can make scripts more reliable. When something goes wrong, it’s important to show helpful messages or try to fix the problem.

Task 1: Checking Exit Status

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

Explanation:

  • #!/bin/bash : This is the shebang line that tells the system to use the Bash shell to run the script.

  • mkdir test_dir: This command tries to create a directory named test_dir

  • $?: This special variable holds the exit status of the last command run. A value of 0 means success, while any other value indicates failure.

  • if [ $? -ne ]; then: This checks if the exit status is not equal to (-ne) 0, meaning the command failed.

  • echo “Error: Failed to create the directory”: This prints an error message if the directory creation failed.

  • echo “Directory created successfully: This prints a success message if the directory was created successfully.

Task 2: Using if Statements for Error Checking

Objective: 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.

Explanation:

  • This script first tries to create a directory. If it fails, it prints an error message and exits the script using exit 1.

  • Next, it attempts to create a file named test_file.txt inside test_dir It uses the same error checking method as before to ensure each step is successful.Task 3: Using trap for Cleanup

Task 3: Using trap for Cleanup

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

Explanation of Task 3 Script

  • Create a Temporary File:

    • temp_file=$(mktemp): This command creates a temporary file and saves its name in the variable temp_file.
  • Set a Trap:

    • trap 'rm -f "$temp_file"; echo "Temporary file deleted."' EXIT: This line ensures that the temporary file is deleted when the script exits, regardless of how it exits. The exit signal makes sure the trap runs when the script finishes.
  • Simulate Data Processing:

    • echo "Processing data..." > "$temp_file": This command writes "Processing data..." into the temporary file.
  • Simulate an Unexpected Exit:

    • The line # exit 1 is commented out, but if you uncomment it, the script will exit unexpectedly, triggering the trap to delete the temporary file.

Save and Exit

  • Exit Insert Mode:

    • Press Esc to exit insert mode.
  • Save and Exit vim:

    • Type :wq and press Enter to save your changes and exit

Task 4: Redirecting Errors

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

Explanation:

  • cat non_existfile.txt 2> error.log: This command attempts to read non_existfile.txt. The 2> operator redirects standard error (file descriptor 2) to error.log. This means any error message will go into this log file.

  • if [ -s error.log ]; then: This checks if error.log is not empty (-s checks if the file size is greater than zero). If it contains any messages, it notifies the user.

  • The script informs the user whether the file was read successfully or if an error occurred.

Task 5: Creating Custom Error Messages

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

Explanation

The script first checks if nonexistfile.txt is there. If it’s not, it shows a message saying the file is missing and suggests checking the file name. After that, the script stops.

If the file is found, the script tries to open it. If there’s any issue, the error is saved in a file called error.log

In the end, the script tells you to look at the error.log file for more information about the error.

Conclusion

Thank you for reading this blog about handling errors in shell scripts. I hope the steps were easy to follow and helped you understand better. I know learning can be hard sometimes, but don’t worry—mistakes help us learn and get better.

I’ll be writing more blogs to make Bash scripting easier to understand, so stay tuned! Just keep learning and trying new things in DevOps.

Happy learning, and thank you