Logging
In this page:
Logging
A simple logging function that prefixes messages with a timestamp makes debugging scripts far easier than scattered echo calls. Directing logs to a file with tee or redirection lets you review what happened after the script finishes. Consistent logging is especially valuable in scripts that run unattended, like cron jobs.
Note: Include a timestamp in every log line so you can correlate script behavior with events elsewhere in the system.
Example: Logging
#!/bin/bash
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
log "Script started"
log "Processing data..."
log "Script finished"
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments