DEV Community

Kanav Gathe
Kanav Gathe

Posted on β€’ Edited 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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (0)

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more