Kanav Gathe
Posted on October 23, 2024
Day 11: Error Handling in Shell Scripts 🚀
Hello DevOps enthusiasts! 👋 Welcome to Day 11 of the #90DaysOfDevOps challenge. Today, we're diving into error handling in shell scripts.
Task Solutions 💻
1. Exit Status Checking
#!/bin/bash
# Create directory and check status
mkdir testdir
if [ $? -ne 0 ]; then
echo "Failed to create directory"
exit 1
fi
echo "Directory created successfully"
2. If Statement Error Checking
#!/bin/bash
# Multiple commands with error checking
if mkdir -p testdir; then
if touch testdir/testfile; then
echo "File created successfully"
else
echo "Failed to create file"
exit 1
fi
else
echo "Failed to create directory"
exit 1
fi
3. Using Trap for Cleanup
#!/bin/bash
# Create temporary file
temp_file=$(mktemp)
# Set trap for cleanup
trap 'rm -f "$temp_file"' EXIT
echo "Working with temporary file"
# Script exits and temp file is removed automatically
4. Error Redirection
#!/bin/bash
# Redirect errors to file
cat nonexistent_file.txt 2> error.log
5. Custom Error Messages
#!/bin/bash
process_file() {
if [ ! -f "$1" ]; then
echo "Error: File $1 does not exist"
exit 1
fi
echo "Processing file $1"
}
Key Takeaways 💡
- Exit status checks prevent cascading failures
- Traps ensure cleanup on script exit
- Error redirection helps in logging
- Custom messages improve debugging
- Proper error handling is crucial for reliability
Bash #DevOps #ErrorHandling #Linux #90DaysOfDevOps
This is Day 11 of my #90DaysOfDevOps journey. Keep handling those errors!
💖 💪 🙅 🚩
Kanav Gathe
Posted on October 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.