The Problem: Disks Saturated by Log Files
![]() |
| Image generated with Gemini AI |
Manual server maintenance is the enemy of efficiency. An IT sysadmin regularly has to free up disk space choked by old Apache/Nginx log files or ensure that critical configuration directories (e.g., /etc) are consistently backed up remotely. Forgetting these tasks leads to unplanned service outages.
The Solution: Bash Scripting and Cronjobs
We need to build a robust script that autonomously handles archiving critical data, purging obsolete files to free up inodes, and synchronizing everything to a secure off-site backup server.
1. The Bash Script for Backup and Cleanup
Create a file named server_maintenance.sh and paste this code. The script utilizes tar for compression, find to identify old logs, and rsync for secure transfer over SSH.
#!/bin/bash
# server_maintenance.sh - Backup and log rotation
BACKUP_DIR="/var/backups/daily"
TIMESTAMP=$(date +"%F")
TARGET_DIR="/etc"
REMOTE_SERVER="backup_user@10.0.10.50:/archive"
# 1. Creating the compressed archive
echo "[*] Creating backup for $TARGET_DIR..."
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/etc_backup_$TIMESTAMP.tar.gz" "$TARGET_DIR"
# 2. Purging old logs (older than 30 days)
echo "[*] Rotating and deleting obsolete logs..."
find /var/log -name "*.log" -type f -mtime +30 -exec rm -f {} \;
# 3. Secure remote transfer
echo "[*] Syncing to the backup server..."
rsync -avz --delete "$BACKUP_DIR/" "$REMOTE_SERVER"
echo "[+] Maintenance completed successfully."
2. Execution Permissions and Scheduling
To make the script executable, modify the permissions:
chmod +x server_maintenance.sh
Now, let's delegate the automatic execution to the cron daemon. Open the cron table for the root user by running sudo crontab -e and add the following directive to trigger the script every night at 02:00 AM:
0 2 * * * /full/path/server_maintenance.sh >> /var/log/maintenance.log 2>&1
With this automation in place, the data lifecycle on your server is completely autonomous, performance-optimized, and disaster-proof.







