Advanced Bash Scripting
Good Practices applied
Logging
Track events with ISO 8601 timestamps by wrapping date
calls in functions. This ensures consistent, machine-friendly logs across environments.
Why Use Timestamped Logs
Timestamped entries help you:
- Debug sequences in real time
- Audit events in containerized workflows
- Reconstruct failures across distributed systems
Quick Demo: Inline Timestamp
Use echo
with command substitution to append UTC time:
echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ") : Script event happening"
Output:
2023-05-20T03:51:03Z : Script event happening
Reusable log
Function
Instead of repeating timestamp logic, encapsulate it:
#!/usr/bin/env bash
log() {
echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ") ${*}" >&2
}
log "Hello World!"
Running ./log.sh
produces:
2023-06-01T05:42:45Z Hello World!
Note
Sending log messages to standard error (>&2
) separates them from regular output and integrates better with redirection.
ISO 8601 Date Format
Using YYYY-MM-DDThh:mm:ssZ
guarantees consistency across locales. Common date
specifiers:
Specifier | Meaning |
---|---|
%Y | Year (4 digits) |
%m | Month (01–12) |
%d | Day of month (01–31) |
%H | Hour (00–23) |
%M | Minute (00–59) |
%S | Second (00–59) |
%Z | Time zone (e.g., UTC) |
Test formats:
date
date -u +"%Y-%m-%dT%H:%M:%SZ"
# 2023-05-19T15:53:19Z
Warning
Avoid over-logging. Too verbose logs can obscure critical information and degrade performance.
Best Practices
- Write logs for humans: clear, concise, and actionable.
- Include only relevant data: timestamps, event messages, and context.
- Use consistent formatting to facilitate automated parsing.
Links and References
Watch Video
Watch video content