Error Handling and Debugging
Section 6: Error Handling and Debugging
Lesson 1: Error Handling in Shell Scripts
Effective error handling in shell scripts involves using traps for specific signals, managing exit codes, and providing meaningful error messages.
1.1 Using Trap for Error Handling
#!/bin/bash
# Error handling with trap
# Define a function to handle errors
handle_error() {
echo "Error occurred. Exiting script."
exit 1
}
# Register the function to handle errors
trap 'handle_error' ERR
# Main script logic
echo "Running script with potential errors."
# Simulate an error (e.g., division by zero)
result=$(echo 1/0)
echo "Result: $result"
1.2 Exit Codes and Error Messages
#!/bin/bash
# Exit codes and error messages
# Function to perform a task with potential errors
perform_task() {
# Simulate an error condition
if [ "$1" -eq 0 ]; then
echo "Error: Division by zero."
exit 1
fi
}
# Main script logic
echo "Running script with exit codes."
# Call the function with an argument
perform_task 0
# Check the exit code and display an error message if needed
if [ $? -ne 0 ]; then
echo "Error: Task failed."
fi
Lesson 2: Debugging Shell Scripts
Debugging shell scripts involves adding debug statements, analyzing variable values, and using tools like set -x for script debugging.
2.1 Adding Debug Statements
#!/bin/bash
# Adding debug statements
# Enable debug mode
set -e
# Main script logic with debug statements
echo "Starting script execution."
# Debug statement 1
echo "Debug: Performing task 1."
# Debug statement 2
echo "Debug: Performing task 2."
# Debug statement 3
echo "Debug: Performing task 3."
# Disable debug mode
set +e
echo "Script execution completed successfully."
2.2 Using set -x for Script Debugging
#!/bin/bash
# Using set -x for script debugging
# Enable debugging
set -x
# Main script logic
echo "Starting script execution."
# Debug statement 1
echo "Debug: Performing task 1."
# Debug statement 2
echo "Debug: Performing task 2."
# Debug statement 3
echo "Debug: Performing task 3."
# Disable debugging
set +x
echo "Script execution completed successfully."
Understanding error handling techniques and incorporating debugging practices improves the reliability and maintainability of shell scripts. In the upcoming sections, we'll explore more advanced scripting techniques and real-world applications.