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

Logging

In this page:

  1. Logging

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"

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.