DEV Community

Kanav Gathe
Kanav Gathe

Posted on

Day 11/90: Error Handling in Shell Scripts 🛡️ #90DaysOfDevOps

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

4. Error Redirection

#!/bin/bash

# Redirect errors to file
cat nonexistent_file.txt 2> error.log
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)