← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 5 of 12

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:

  1. Logging
Syntax
bash
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

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

log "Script started"
log "Processing data..."
log "Script finished"
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
  1. Writing logs with > so the file is overwritten each time; use >>.
  2. Mixing errors and output without 2>&1.
  3. Logging without timestamps, which makes problems hard to trace.

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.