Timestamped logging functions for scripts
Small log, warn and die helpers that write ISO timestamps to stderr and keep stdout clean for data.
- Bash
- GreenSnippets
- MIT
log() { printf '%s [INFO] %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
warn() { printf '%s [WARN] %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
die() { printf '%s [ERROR] %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 1; }Example / expected output
log "Starting backup"
[[ -d /data ]] || die "/data does not exist"
<!-- 2025-03-01T10:15:00Z [INFO] Starting backup -->How it works
Writing logs to stderr keeps stdout usable for piping results. date -u +%FT%TZ gives an ISO 8601 UTC timestamp that sorts correctly and is unambiguous across machines. die logs and exits with a non-zero status so callers and CI notice.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- Bash
Retry a shell command with backoff
Re-run a flaky command a few times with increasing delays and a clear failure exit code.
- Bash
Parse command-line flags with getopts
Handle -v, -o FILE and -h in a bash script with getopts and a usage message.
- Bash
Run commands in parallel with xargs
Process many files concurrently with xargs -P, safely handling spaces and newlines in names.
- Bash
Clean up temporary files with trap
Create a temp directory and guarantee it is removed when the script exits, fails or is interrupted.

