☑️Day11 Of #90DaysOfDevOps challenge: Error Handling in Shell Scripting.
Understanding how to handle errors in shell scripts is crucial for creating robust and reliable scripts. Today, I’m going to learn how to use various techniques to handle errors effectively in bash scripts.
Task01: Handling error using Exit Status.!
Writing a script that tries to create a directory and checks if it worked. If it didn't, print an error message.
#!/bin/bash # creating a directory mkdir /home/ubuntu/day11/task1 if [ $? -ne 0 ]; then echo "Failed to create directory /home/ubuntu/day11/task1" else echo "Directory /home/ubuntu/day11/task1 created successfully" fi
Output:
Error handling
Task02: Handling Error Using if statements for error Checking
- Creating a file inside the directory and use if statements to handle errors at each step.
#!/bin/bash
mkdir /home/ubuntu/day11/task2
if [ $? -ne 0 ];then
echo "Error: Failed to create directory /task2"
exit 1
fi
#creating a file inside task2 direcory
touch /home/ubuntu/day11/task2/my_file.txt
if [ $? -ne 0 ]; then
echo "Error: Failed to create file inside of directory."
fi
echo "Directory and File Created successfully"
Output:
Error handling:
Task03: Handling error using trap
for cleanup.
Writing a script that creates a temporary file and sets a
trap
to delete the file if the script exits unexpectedly.#!/bin/bash #creating temporary file temp_file="/home/ubuntu/day11/task3/tempfile_$$.txt" touch "$temp_file" echo "Temporary file created at $temp_file" #setting up a trap to delete the temporary file on exit trap 'echo "Deleting temporary file"; rm -f "$temp_file"' EXIT #Main script with sleep simulat echo "Script is running..." sleep 10 #exit echo "Script completed successfully."
Task 4: Redirecting Errors
Writing a script that tries to read a non-existent file and redirects the error message to a file called
error.log
#/bin/bash #attempting to read nonExistent file and redirect the error in error.log file cat non_existent_file.txt 2> error.log
Output:
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
mkdir /home/ubuntu/day11/task5/directory1
if [ $? -ne 0 ]; then
echo "Error: Directory could not be created. Check if you have the necessary permission"
exit 1
fi
#to create a file inside directory
touch /home/ubuntu/day11/task5/directory1/myFile.txt
if [ $? -ne 0 ];then
echo "Error: File in the directory could not be created. ENsure the directory exists and you have write permissions."
exit 1
fi
echo "Directory and file created successfully..!"
Output:
Handling errors in shell scripts is essential for ensuring that your scripts run smoothly and handle unexpected situations gracefully. As you continue working with shell scripting, always remember that proactive error handling not only improves the functionality of your scripts but also saves time debugging and troubleshooting later.