Bash Script to Clean and Archive Old Log Files in Linux
Log files show what’s happening on your system. Over time, they can take up space and slow things down. You can use a Bash script to automatically archive log files and keep your system clean.
Prerequisites Archive Log Files
Before you begin, make sure you have:
- A Linux system or server.
- Basic knowledge of using the terminal.
- Access to the directory where log files are stored.
- Permission to create files in that directory.
Why Archive Log Files?
Old log files can:
- Consume Disk Space: Logs can grow quickly and fill up storage.
- Cause System Slowdowns: High disk usage may affect performance.
- Make Backups Difficult: Large, unorganized logs increase backup time.
Archiving old logs instead of deleting them ensures you save space while still keeping historical data for auditing or compliance needs.
ALSO READ:
- Easily Automatically Delete Linux Log Files Older Than 30 Days Using a Bash Script
- Simple and Powerful Git and GitHub Guide for Beginners 2025
- 1 Powerful Shell Script to Monitor Missing Mount Points in Linux
Click here to go to the GitHub repos link
Create the Bash Script Archive Log Files
#!/bin/bash
# Directory where logs are stored
log_path="/path/to/logs"
# Directory where archives will be stored
archive_path="/path/to/archives"
# Threshold in percentage
threshold_limit=85
# Check disk usage of /u01 (replace with your mount point if different)
mount_point_usage=$(df -h /u01 | awk 'NR==2 {print $5}' | tr -d %)
# If usage exceeds threshold, archive old logs
if [ "$mount_point_usage" -gt "$threshold_limit" ]; then
mkdir -p "$archive_path"
find "$log_path" -type f -mtime +30 | tar -czf "$archive_path/old_logs_$(date +%F).tar.gz" -T -
echo "Archived logs older than 30 days: $archive_path/old_logs_$(date +%F).tar.gz"
else
echo "Disk usage is ${mount_point_usage}%. No archiving required."
fi
Make the Script Executable & Run It
chmod +x 30_days_old _log_files_Archive_script.sh
./30_days_old _log_files_Archive_script.sh
Automate with Cron
To automate the Archive Log Files process, schedule the script using cron.
crontab -e
0 0 * * * /path/to/30_days_old _log_files_Archive_script.sh > /var/log/archive_status$(date +%F).log 2>&1
This ensures your logs are archive log files automatically without any manual effort.
Best Practices
- Backup Critical Logs: Keep copies of important logs before archiving.
- Adjust Retention Period: Modify
-mtime +30
to archive logs older than a different number of days. - Monitor Disk Usage: Combine with monitoring tools (Nagios, Prometheus, etc.) for alerts.
- Test First: Run manually to verify before scheduling with cron.
