BASH
Automate Daily Log Archiving and Cleanup
A Bash script to automatically compress and archive old application logs, then delete files older than a specified duration to manage disk space efficiently.
#!/bin/bash
LOG_DIR="/var/log/myapp"
ARCHIVE_DIR="/var/log/myapp/archive"
RETENTION_DAYS=30
# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR"
# Archive logs from yesterday
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)
LOG_FILE_PATTERN="access.log" # Or error.log, etc.
if [ -f "${LOG_DIR}/${LOG_FILE_PATTERN}-${YESTERDAY}" ]; then
echo "Archiving ${LOG_DIR}/${LOG_FILE_PATTERN}-${YESTERDAY}...
"
tar -czf "${ARCHIVE_DIR}/${LOG_FILE_PATTERN}-${YESTERDAY}.tar.gz" -C "$LOG_DIR" "${LOG_FILE_PATTERN}-${YESTERDAY}"
rm "${LOG_DIR}/${LOG_FILE_PATTERN}-${YESTERDAY}"
else
echo "No log file found for yesterday: ${LOG_FILE_PATTERN}-${YESTERDAY}
"
fi
# Clean up archives older than RETENTION_DAYS
echo "Cleaning up archives older than ${RETENTION_DAYS} days...
"
find "$ARCHIVE_DIR" -type f -name "*.tar.gz" -mtime +"$RETENTION_DAYS" -delete
echo "Log archiving and cleanup complete.
"
How it works: This script automates the process of daily log management. It first creates an archive directory if necessary. Then, it identifies log files from the previous day (assuming a daily rotation scheme like `access.log-YYYY-MM-DD`), compresses them into a gzipped tarball, and moves them to an archive directory. Finally, it uses `find` to locate and delete any archived log files that are older than the specified `RETENTION_DAYS`, helping to prevent disk space exhaustion.