Log files are the heartbeat of Linux server health, but they can quickly become a storage burden if not managed. Without an automated strategy, disk space can be exhausted by runaway processes or debug sessions left running for weeks. The solution lies in a custom Bash script that orchestrates log rotation, compresses old entries, and archives them to long-term storage before deleting data older than your retention policy. This guide provides a concrete, runnable example suitable for IT students and junior engineers, focusing on safety, debugging, and integration into standard workflows like Git repositories or cron jobs.
Understanding Log Rotation and the Risks of Manual Cleanup
Before writing code, it is essential to understand the mechanics of log rotation. On Linux systems, tools like logrotate handle this automatically for standard services (e.g., /var/log/syslog, /var/log/nginx/access.log). However, application-specific logs often reside in non-standard directories or require custom retention policies that the default configuration cannot handle.
The primary risks of manual cleanup include:
* Data Loss: Accidentally deleting active logs while a process is still writing to them.
* Disk Exhaustion: Forgetting to run logrotate or cleaning up, leading to No space left on device errors that crash services.
* Inconsistency: Different servers in a cluster having different cleanup schedules, complicating troubleshooting.
A Bash script bridges this gap by providing a consistent, version-controlled method for managing logs across your infrastructure.
Prerequisites and Environment Setup
To follow along, you will need a standard Linux environment (Ubuntu, Debian, or CentOS) with Bash installed. While logrotate is pre-installed on most distributions, this guide focuses on creating a custom script that can be called independently or alongside it.
Prerequisites:
* Bash: Version 4.0 or higher (standard on modern Linux).
* Compression tools: gzip or bzip2 for archiving.
* Permissions: The script should generally run as root or a dedicated service account with read/write access to the log directories.
* Storage Destination: A directory configured for archive storage (e.g., /var/archive/logs).
Safety First: Always test scripts in a non-production environment first. Never run destructive commands without a dry-run flag or backup verification step.
Designing the Script Logic: Compression and Archiving
The core logic of our script involves three steps: identifying logs to rotate, compressing them, and moving them to an archive directory. We will create a script named rotate_logs.sh.
First, define the variables at the top of the script. These allow you to easily adjust paths and retention periods without editing the logic itself.
#!/bin/bash
# Configuration Variables
LOG_DIR="/var/log/myapp" # Directory containing application logs
ARCHIVE_DIR="/var/archive/logs" # Destination for compressed archives
RETENTION_DAYS=30 # Days to keep uncompressed logs before archiving
MAX_ARCHIVE_AGE=90 # Days to keep archived files before deletion
DRY_RUN=true # Set to 'false' to execute deletions
echo "=== Log Rotation Script Started ==="
echo "Log Directory: $LOG_DIR"
echo "Archive Directory: $ARCHIVE_DIR"
echo "Retention Period: ${RETENTION_DAYS} days"
echo "Max Archive Age: ${MAX_ARCHIVE_AGE} days"
Next, we implement the rotation logic. The script iterates through log files in LOG_DIR. If a file exceeds a certain size (e.g., 10MB) or has not been rotated recently, it gets compressed.
# Ensure archive directory exists
mkdir -p "$ARCHIVE_DIR"
# Function to rotate a single log file
rotate_log() {
local file="$1"
# Check if file exists and is writable
if [[ ! -f "$file" ]]; then
return 0
fi
# Create a timestamped backup name
local timestamp=$(date +%Y%m%d_%H%M%S)
local backup_name="${file}.${timestamp}"
# Move and compress the log file
# Using gzip for standard compression
if mv "$file" "$backup_name"; then
echo "Rotated: $file -> $backup_name"
# Create a new empty log file to prevent permission denied errors on next write
touch "$file"
chmod 640 "$file"
# If not in dry-run mode, move to archive and compress further if needed
if [[ "$DRY_RUN" == "false" ]]; then
# Move uncompressed rotated file to archive immediately for safety
mv "$backup_name" "${ARCHIVE_DIR}/uncompressed/"
# Optional: Compress files in the archive directory periodically
# This script focuses on immediate rotation; compression can be handled by cron
else
echo "[DRY RUN] Would move $backup_name to ${ARCHIVE_DIR}/uncompressed/"
fi
else
echo "Error rotating $file" >&2
fi
}
# Iterate over all files matching the log pattern (e.g., *.log)
for logfile in "$LOG_DIR"/*.log; do
if [[ -f "$logfile" ]]; then
rotate_log "$logfile"
fi
done
Implementing Archive Cleanup and Verification
A rotation script is incomplete without a cleanup mechanism. Over time, the archive directory will fill up. We need a secondary logic block to delete archives older than MAX_ARCHIVE_AGE. This prevents indefinite storage growth.
We will add this logic using the find command, which is efficient for locating files based on modification time (-mtime).
echo "Checking archive directory for cleanup..."
# Find files in archive directory older than MAX_ARCHIVE_AGE days
# -type f: regular files only
# -name "*.gz": targeting compressed archives (if you implement compression inside the script)
# -mtime +N: modified N days ago or older
find "$ARCHIVE_DIR" -type f -name "*.gz" -mtime +${MAX_ARCHIVE_AGE} | while read file; do
if [[ "$DRY_RUN" == "false" ]]; then
echo "Deleting old archive: $file"
rm -f "$file"
else
echo "[DRY RUN] Would delete: $file"
fi
done
# Cleanup very old uncompressed logs in the specific subdirectory if created
find "${ARCHIVE_DIR}/uncompressed" -type f -mtime +${MAX_ARCHIVE_AGE} | while read file; do
if [[ "$DRY_RUN" == "false" ]]; then
echo "Deleting old uncompressed archive: $file"
rm -f "$file"
else
echo "[DRY RUN] Would delete: $file"
fi
done
echo "=== Log Rotation Script Completed ==="
Verification, Debugging, and Common Errors
After writing the script, saving it to a file (e.g., /usr/local/bin/rotate_logs.sh), and making it executable (chmod +x /usr/local/bin/rotate_logs.sh), you must verify it works correctly.
Verification Steps:
1. Dry Run Test: Execute the script with DRY_RUN=true. Review the output to ensure files are identified for rotation but not deleted.
2. Manual Rotation: Set DRY_RUN=false and run the script once. Check that the original log file is empty (or reset) and the backup exists in the archive directory.
3. Error Handling: Intentionally break a rule (e.g., remove write permissions on the log directory) to see how the script handles mv or touch failures.
Common Errors and Fixes:
* “Permission denied”: Ensure the user running the script has ownership of /var/log/myapp. If using systemd timers, run as root.
* “No such file or directory”: Verify that LOG_DIR paths are correct and that the archive directory exists before the script runs. Use mkdir -p to create missing directories if necessary.
* Race Conditions: If multiple scripts try to rotate the same log simultaneously, they might overwrite each other. Add a lock file mechanism using flock if high concurrency is expected.
Integrating with Cron and Git for Maintenance
To make this automation sustainable, integrate the script into your existing infrastructure management practices.
Cron Integration:
Add a cron job to run the rotation daily at 3:00 AM. Edit /etc/crontab or create a file in /etc/cron.d/:
0 3 * * * root /usr/local/bin/rotate_logs.sh >> /var/log/rotation.log 2>&1
Git Integration:
Store your script in a Git repository. This allows you to version control your automation logic, review changes via pull requests, and deploy updates across multiple servers simultaneously. Include a README.md in the repo explaining how to configure paths for different environments (dev, staging, prod).
Student Practice Task: Build Your Own Lab
To solidify these concepts, students should set up a virtual machine using Docker or VirtualBox with Ubuntu Server.
1. Create a dummy log directory and generate fake logs by running a script that appends random text to files every second.
2. Write a Bash script that rotates logs older than 1 minute.
3. Implement the cleanup logic for archives older than 5 minutes.
4. Test the script manually, then schedule it using systemd-timer instead of cron for better resource management.
By following these steps, you will have a robust, safe, and maintainable log rotation solution that protects your server’s disk health while adhering to best practices in system administration.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

