Skip to content

Error Logging

Error Logging and Reporting

Effective error handling in BASH scripts requires more than just exiting on failure—it demands structured logging, clear user feedback, and consistent message formatting. This section explores techniques to record errors, communicate their context, and ensure visibility across environments.


Logging Errors to Files

Redirecting error output to log files is essential for debugging and auditing. Use exec to redirect stderr (file descriptor 2) to a persistent log file:

exec 2>> /var/log/my_script.log

For temporary logs, use redirection within command execution:

some_command 2>> /tmp/script_errors.log || echo "Command failed" >&2

Best Practice: Rotate logs using logrotate to prevent disk space exhaustion. Example /etc/logrotate.d/my_script:

/var/log/my_script.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
}


Structured Error Messages

Format error messages with timestamps, error codes, and contextual details for clarity. Use printf or echo with variables:

error_message() {
    local ERR_CODE=$1
    local MSG=$2
    echo "[$(date +'%Y-%m-%d %T')] ERROR: Code $ERR_CODE - $MSG" >&2
}

Example usage:

if ! grep -q "pattern" file.txt; then
    error_message 404 "File not found"
    exit 1
fi

Tip: Use colors for visual distinction in terminals (requires tput or printf with ANSI codes):

RED='\033[0;31m'
echo -e "${RED}ERROR: Critical failure${NC}" >&2


User Feedback and Exit Codes

Provide actionable feedback to users while adhering to standard exit codes (0 for success, 1–255 for errors). Combine trap with cleanup logic:

trap 'error_message 1 "Script interrupted" && exit 1' INT TERM

Example script with feedback:

#!/bin/bash
if ! curl -s http://example.com > /dev/null; then
    echo "⚠️ Failed to reach server. Check connectivity." >&2
    exit 1
fi

Advanced: Use notify-send (X11) or growlnotify (macOS) for desktop notifications:

notify-send "Script Error" "Critical failure occurred!" -t 5000


Best Practices Summary

  • Centralize logs: Use consistent paths and rotation policies.
  • Be specific: Include timestamps, codes, and context in messages.
  • Balance feedback: Inform users without overwhelming them with details.
  • Automate cleanup: Use trap to ensure resources are released on errors.

Key takeaways

  • Redirect stderr to files or system logs for persistent error tracking.
  • Format messages with timestamps, codes, and context for clarity.
  • Use trap to handle interrupts and ensure cleanup on failures.
  • Combine exit codes with user-facing feedback for robust error reporting.