Master Bash Script Logging with Timestamps: A Complete Guide
When writing shell scripts, one of the most important aspects to keep in mind is logging. Logging helps you keep track of script execution, especially when things go wrong. The addition of timestamps to your log entries makes it even more useful by allowing you to track when certain events occurred. In this guide, we will explore how to implement bash script logging with timestamps, with examples and explanations. Whether you're troubleshooting, monitoring, or simply improving your script's usability, logging is a powerful tool that can save you time and effort.
Why Should You Use Logging in Bash Scripts?
Logging in bash scripts is essential for several reasons:
- Debugging: When something goes wrong, logs with timestamps help identify when and where the problem occurred.
- Audit Trails: Keeping track of events over time can help you monitor the health of systems and the progress of scripts.
- Automation and Monitoring: Scripts often run automatically at scheduled intervals. Logs help you confirm their correct execution.
- Learning and Improving: Logs provide insights into how scripts behave and where improvements can be made.
Now that you know why logging is important, let’s dive into how to implement logging with timestamps in bash scripts!
Basic Bash Script Logging with Timestamps
Let's start with the basic concept of logging. Typically, you use the echo command to print messages to the console. In bash scripts, you can easily redirect these messages to a log file. To enhance these logs, we can add a timestamp to each log entry, so you know exactly when each event occurred. Here’s how to do it:
#!/bin/bash
# Simple bash script with timestamp logging
log_file="script.log"
# Function to log messages with a timestamp
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $log_file
}
# Example usage
log_message "Script started"
log_message "Doing some work..."
log_message "Script completed"
In this script, we define a function log_message that takes a message as an argument, prepends the current date and time using date, and appends the message to a log file called script.log.
Understanding the Timestamp Format
In the example above, we use the date command to generate the timestamp. The +%Y-%m-%d %H:%M:%S format specifies how the timestamp will appear. Let’s break it down:
- %Y: Year (e.g., 2025)
- %m: Month (e.g., 04)
- %d: Day of the month (e.g., 28)
- %H: Hour in 24-hour format (e.g., 15)
- %M: Minute (e.g., 30)
- %S: Second (e.g., 45)
The timestamp produced by $(date '+%Y-%m-%d %H:%M:%S') might look like this: 2025-04-28 15:30:45. This format is very readable and provides a precise record of when each log entry was made.
Advanced Logging: Including Log Levels
As your scripts grow in complexity, you might want to differentiate between different types of messages, such as errors, warnings, or informational logs. One way to do this is by using log levels. Let’s enhance our logging system by including log levels in our log messages:
#!/bin/bash
# Bash script with timestamp and log levels
log_file="script.log"
# Function to log messages with timestamp and log levels
log_message() {
local log_level=$1
local message=$2
echo "$(date '+%Y-%m-%d %H:%M:%S') [$log_level] - $message" >> $log_file
}
# Example usage
log_message "INFO" "Script started"
log_message "INFO" "Performing a task..."
log_message "ERROR" "Something went wrong!"
log_message "INFO" "Script completed"
In this example, we’ve added a log_level parameter to the log_message function. The log levels can be customized, but typical ones are:
- INFO: Informational messages, such as when a script starts or completes.
- WARNING: Warnings about potential issues, but not critical failures.
- ERROR: Messages indicating something went wrong.
- DEBUG: Detailed information useful for debugging.
Now, when you read the log file, you’ll be able to quickly identify the severity of each message and filter logs based on log levels.
Log Rotation: Managing Large Log Files
As your scripts run over time, they will accumulate log entries. If your script is used frequently, the log file can grow very large. To manage this, you can implement log rotation. This ensures that old log files are archived, and new logs are written to a fresh file. Here's an example of how to implement log rotation in a bash script:
#!/bin/bash
# Bash script with log rotation
log_file="script.log"
log_archive="script_$(date '+%Y-%m-%d').log"
# Rotate the log file if it's too large
if [ -f $log_file ] && [ $(stat -c %s "$log_file") -gt 1000000 ]; then
mv $log_file $log_archive
touch $log_file
log_message "INFO" "Log file rotated. Old logs archived to $log_archive."
fi
# Function to log messages with timestamp
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $log_file
}
# Example usage
log_message "INFO" "Script started"
log_message "INFO" "Running tasks..."
log_message "INFO" "Script completed"
This script checks the size of the log file using stat -c %s and compares it to a threshold (in this case, 1MB). If the file exceeds this size, it’s archived and a new log file is created. This helps keep your logs manageable over time.
Viewing and Analyzing Logs
Once you have logging set up, you can easily view the logs with commands like cat, less, or tail. For example, to view the most recent logs, you can use:
tail -f script.log
The -f flag causes tail to display new log entries as they are added to the file. This is useful when you’re monitoring long-running scripts in real-time.
Conclusion: Why Logging is Crucial for Bash Scripts
Incorporating logging with timestamps into your bash scripts is essential for ensuring reliability, debugging issues, and keeping track of important events. By following the steps outlined in this guide, you can add timestamps to your logs, incorporate log levels for more detailed information, and even manage large log files with rotation. Whether you’re working on small scripts or large automation tasks, logging is a critical practice that can save you time and headaches in the long run.
Start implementing logging in your bash scripts today and watch as your scripting experience becomes more efficient and reliable!

Komentarze (0) - Nikt jeszcze nie komentował - bądź pierwszy!