Learning Objectives
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
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.
Using
if
Statements for Error Checking: Learn how to useif
statements to handle errors.Using
trap
for Cleanup: Understand how to use thetrap
command to handle unexpected errors and perform cleanup.Redirecting Errors: Learn how to redirect errors to a file or
/dev/null
.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
mkdir /tmp/mydir
if [ $? -ne 0 ]; then
echo "Failed to create directory /tmp/mydir"
fi
ubuntu@ip-172-31-44-248:~/scripts$ bash ./exitstatus.sh
mkdir: cannot create directory '/tmp/mydir': File exists
Failed to create directory /tmp/mydir
ubuntu@ip-172-31-44-248:~/scripts$
Task 2: Usingif
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
mkdir /tmp/mydir1
if [ $? -ne 0 ]; then
echo "Failed to create directory /tmp/mydir"
else
echo "Directory Created Successfully."
fi
ubuntu@ip-172-31-44-248:~/scripts$ bash ./exitstatus1.sh
Directory Created Successfully.
ubuntu@ip-172-31-44-248:~/scripts$ bash ./exitstatus1.sh
mkdir: cannot create directory '/tmp/mydir1': File exists
Failed to create directory /tmp/mydir
Task 3: Usingtrap
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
tempfile=$(mktemp)
trap "rm -f $tempfile" EXIT
echo "This is a temporary file." > $tempfile
cat $tempfile
# Simulate an error
exit 1
ubuntu@ip-172-31-44-248:~/scripts$ bash ./exitstatus2.sh
This is a temporary file.
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
.
In general, here are some common redirection operators in bash:
>
: Redirects standard output (file descriptor 1).2>
: Redirects standard error (file descriptor 2).&>
: Redirects both standard output and standard error to the same file.
#!/bin/bash
cat non_existent_file.txt 2> error.log
ubuntu@ip-172-31-44-248:~/scripts$ bash ./exitstatus3.sh
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 /tmp/mydir
if [ $? -ne 0 ]; then
echo "Error: Directory /tmp/mydir could not be created. Check if you have the necessary permissions."
fi