← Back to Bash Course | Chapter 14: Best Practices & Real-World Scripting | Lesson 5 of 7

Logging in Scripts (Timestamped log Function)

A logging function prints messages with the time attached, so you can tell later exactly when each step of a script happened.

A Basic Timestamped Logger

A log function that prefixes every message with the current timestamp keeps output consistent and makes it possible to reconstruct the sequence and timing of events after the fact.

Example: A Basic Timestamped Logger

bash
#!/bin/bash
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

log "script starting"
log "doing some work"
log "script finished"

Logging to stderr

Sending log output to stderr instead of stdout keeps it separate from the script's actual results, so stdout can still be piped or captured cleanly by another program.

Example: Logging to stderr

bash
#!/bin/bash
log() {
    echo "[$(date +'%H:%M:%S')] $1" >&2
}

log "this is a diagnostic message"
echo "this is the actual result"

Adding Log Levels

Extending the logging function to accept a severity level (INFO, WARN, ERROR) makes it easy to filter or visually distinguish message importance later, without changing every call site's structure.

Example: Adding Log Levels

bash
#!/bin/bash
log() {
    local level=$1
    shift
    echo "[$(date +'%H:%M:%S')] [$level] $*"
}

log INFO "starting process"
log WARN "low disk space detected"
log ERROR "failed to connect, but continuing demo"

Sending Logs to a File and the Screen

Piping the logger's output through tee -a writes each message to a persistent log file while still showing it immediately, combining two previously covered techniques.

Example: Sending Logs to a File and the Screen

bash
#!/bin/bash
log() {
    echo "[$(date +'%H:%M:%S')] $1" | tee -a run.log
}

log "first event"
log "second event"
echo "--- saved log file ---"
cat run.log
rm -f run.log
Common Mistakes
  1. Using plain echo for status messages throughout a script, making it impossible to tell later when each event occurred.
  2. Writing log messages to stdout when they should go to stderr (or a dedicated log file), mixing diagnostics with actual program output.
  3. Forgetting to flush or account for buffering when logging from background jobs, which can cause log lines to interleave unpredictably.
Chapter Summary
  • A small log function wrapping date plus the message keeps timestamp formatting consistent across an entire script.
  • Logging to stderr keeps diagnostic output separate from a script's actual stdout results.
  • date +"%Y-%m-%d %H:%M:%S" is a common, sortable timestamp format for log lines.
  • Centralizing logging in one function makes it easy to later redirect all log output to a file, syslog, or both.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.