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.

The image features a diagram with a clock icon and connected nodes, accompanied by the text "Enabling us to track the flow and sequence of events," under the heading "Logging."

ISO 8601 Date Format

Using YYYY-MM-DDThh:mm:ssZ guarantees consistency across locales. Common date specifiers:

SpecifierMeaning
%YYear (4 digits)
%mMonth (01–12)
%dDay of month (01–31)
%HHour (00–23)
%MMinute (00–59)
%SSecond (00–59)
%ZTime 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.

The image shows a signpost with two directions: "Judiciously and succinctly" marked with a red cross, and "Quality and relevance" marked with a green check.

Watch Video

Watch video content

Previous
Comments