Linux Tips guides, explanations and reader checklists on whilenetworking.com

Creating a Bash Script to Automate Daily System Maintenance and Log Rotation

System maintenance is often the most overlooked aspect of Linux administration until a disk fills up or performance degrades. Relying on manual cron jobs…

System maintenance is often the most overlooked aspect of Linux administration until a disk fills up or performance degrades. Relying on manual cron jobs to rotate logs and clean temporary files introduces human error, while ad-hoc commands lack auditability. The industry-standard solution is a robust Bash script that encapsulates these tasks into a single, version-controlled unit. This article guides you through building a secure, modular script for daily system health checks and log rotation, suitable for both student labs and production environments.

Understanding the Core Requirements

Before writing code, it is essential to define the scope of “maintenance.” A comprehensive script should address three primary areas:
1. Log Rotation: Preventing disk exhaustion by archiving logs older than a specific retention period (e.g., 7 days) and rotating current application logs.
2. Disk Cleanup: Removing temporary files, empty directories, and old package manager caches that accumulate over time.
3. Health Monitoring: Checking critical system metrics like memory usage, disk space on root partitions, and process zombie counts.

Important Security Note: Always execute these scripts as the root user or via a dedicated service account with principle-of-least-privilege permissions. Never run these commands directly in a terminal for production systems without logging the output. The following examples assume a standard Debian/Ubuntu-based system using systemd, which is common in industry.

Prerequisites and Environment Setup

To ensure the script works reliably across different distributions, we must handle dependencies carefully. We will use bash as the shell (standard on most Linux systems) and rely on core utilities like find, du, journalctl, and logrotate.

Ensure your environment has write access to /etc/cron.d/ or that you are using a systemd timer. For this guide, we will create the script file at /usr/local/bin/system-maintenance.sh.

#!/bin/bash
# File: /usr/local/bin/system-maintenance.sh
# Description: Daily system maintenance and log rotation script

set -euo pipefail  # Exit on error, undefined vars, or failed pipeline
SCRIPT_DATE=$(date +"%Y%m%d")
LOG_FILE="/var/log/maintenance.log"
TEMP_DIR="/tmp/maintenance_tmp"

# Create a temporary directory for this run to avoid file collisions
mkdir -p "$TEMP_DIR"

The set -euo pipefail command is critical. It stops the script immediately if a command fails, preventing partial execution that could leave the system in an inconsistent state. We define a LOG_FILE variable so all actions are recorded for auditing.

Implementing Log Rotation Logic

Log rotation is typically handled by the logrotate package, but custom scripts allow for more granular control over specific application logs or retention policies outside of standard /var/log.

The script should identify log files older than a threshold (e.g., 7 days) and compress them using gzip, then delete the originals. This prevents disk space from being consumed by logs that have already been rotated by the system daemon.

# Function to rotate application logs older than X days
rotate_old_logs() {
    local retention_days=7
    echo "$(date): Starting rotation of logs older than $retention_days days..." >> "$LOG_FILE"

    # Find .log files in /var/log that are not owned by root and older than 7 days
    # Exclude logrotate's own state file to avoid loops
    find /var/log -type f -name "*.log" -mtime +${retention_days} -exec gzip {} \; 2>/dev/null || true

    # Remove the uncompressed old logs after compression
    find /var/log -type f -name "*.log.gz" -mtime +${retention_days} -delete 2>/dev/null || true

    echo "$(date): Completed log rotation." >> "$LOG_FILE"
}

Expected Output: If successful, the script will append a timestamped message to /var/log/maintenance.log. If find encounters permission errors on specific directories (common in restricted environments), the || true ensures the script continues rather than crashing.

Performing Disk Cleanup and Cache Management

Over time, package managers like apt or dnf retain cached .deb or .rpm files, and temporary directories fill up with build artifacts. The script must safely clean these without touching active system files.

# Function to clean package caches and temp files
clean_system() {
    echo "$(date): Starting disk cleanup..." >> "$LOG_FILE"

    # Clean apt cache (Debian/Ubuntu)
    if command -v apt-get &>/dev/null; then
        apt-get clean 2>> "$LOG_FILE" || true
        apt-get autoremove --purge -y 2>> "$LOG_FILE" || true
    fi

    # Clean dnf cache (RHEL/Fedora/CentOS)
    if command -v dnf &>/dev/null; then
        dnf clean all 2>> "$LOG_FILE" || true
    fi

    # Remove empty directories in /tmp older than 3 days
    find /tmp -type d -empty -mtime +3 -delete 2>> "$LOG_FILE" || true

    echo "$(date): Completed disk cleanup." >> "$LOG_FILE"
}

Verification Step: After running the script, execute df -h to ensure the / partition usage has not increased unexpectedly. This confirms that old logs were removed and disk space was reclaimed.

Monitoring System Health Metrics

A maintenance script is incomplete without checking for potential issues. We will check for high memory usage, excessive zombie processes, and low disk space on the root filesystem.

# Function to check system health
check_health() {
    echo "$(date): Checking system health..." >> "$LOG_FILE"

    # Check Root Disk Usage (Alert if > 90%)
    local disk_usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ "$disk_usage" -gt 90 ]; then
        echo "WARNING: Root disk usage is ${disk_usage}%" >> "$LOG_FILE"
        # Optional: Send alert via email or Slack hook here
    fi

    # Check for Zombie Processes
    local zombie_count=$(ps aux | awk '$8 ~ /Z/ {count++} END {print count+0}')
    if [ "$zombie_count" -gt 5 ]; then
        echo "WARNING: Found $zombie_count zombie processes." >> "$LOG_FILE"
    fi

    echo "$(date): Health check completed." >> "$LOG_FILE"
}

Common Mistake: Beginners often use grep to count lines, which can be slow on large outputs. Using awk or ps with specific flags is more efficient. Also, always redirect error output (2>>) to the log file so that permission denied errors do not clutter the terminal.

Scheduling and Automation

The final step is automating the script execution. On modern Linux systems, systemd timers are preferred over traditional cron because they handle logging and resource management better.

  1. Create a systemd unit file at /etc/systemd/system/maintenance-daily.service:
    “`ini
    [Unit]
    Description=Daily System Maintenance
    After=network.target

    [Service]
    Type=oneshot
    ExecStart=/usr/local/bin/system-maintenance.sh
    StandardOutput=journal
    StandardError=journal
    “`

  2. Create a timer unit at /etc/systemd/system/maintenance-daily.timer:
    “`ini
    [Unit]
    Description=Run maintenance daily

    [Timer]
    OnCalendar=–-* 03:00:00 # Runs every day at 3 AM
    Persistent=true

    [Install]
    WantedBy=timers.target
    “`

Enable and start the timer: systemctl enable --now maintenance-daily.timer. This ensures the script runs automatically without manual intervention.

Student Practice Task

To reinforce learning, students should modify the script to include a custom alert mechanism. For example, create a function that checks if free memory is below 10% and writes an alert to a dedicated file or sends a notification to a configured email address using mail or sendmail. This exercise teaches how to extend functionality while maintaining the safety of the core logic.

Conclusion

Automating system maintenance transforms reactive administration into proactive management. By encapsulating log rotation, disk cleanup, and health checks into a single Bash script, administrators ensure consistency, reduce human error, and maintain detailed audit trails. Always test these scripts in an isolated lab environment before deploying to production, and remember that specific package names and paths may vary slightly between distributions like Ubuntu, CentOS, or Fedora.

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.