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:
For temporary logs, use redirection within command execution:
Best Practice: Rotate logs using logrotate to prevent disk space exhaustion. Example /etc/logrotate.d/my_script:
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:
Tip: Use colors for visual distinction in terminals (requires tput or printf with ANSI codes):
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:
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:
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
trapto ensure resources are released on errors.
Key takeaways¶
- Redirect
stderrto files or system logs for persistent error tracking. - Format messages with timestamps, codes, and context for clarity.
- Use
trapto handle interrupts and ensure cleanup on failures. - Combine exit codes with user-facing feedback for robust error reporting.