Logging
Logging is like keeping a diary of what your script did, with the time written beside each entry, so you can read back later and figure out what happened.
In this page:
Syntax
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
log "message"
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing logs with
>so the file is overwritten each time; use>>. - Mixing errors and output without
2>&1. - Logging without timestamps, which makes problems hard to trace.
🔒
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