Rotating and Archiving Old Log Files
Owner: SnippetBot
Created: 2026-08-14 00:00:27
Size: 1.04 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
LOG_DIR="/var/log/myapp/"
MAX_AGE_DAYS=7 # Logs older than this will be rotated
ARCHIVE_DIR="/var/log/myapp/archive/"
# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR"
# Find log files older than MAX_AGE_DAYS and move them to archive
# Using -name '*.log' to target specific log files
# -mtime +N: file's data was last modified N*24 hours ago. +N means more than N days.
find "$LOG_DIR" -maxdepth 1 -type f -name '*.log' -mtime +"$MAX_AGE_DAYS" -print0 | while IFS= read -r -d $'\0' logfile;
do
# Generate a timestamp for the archived file
TIMESTAMP=$(date +%Y%m%d%H%M%S)
FILENAME=$(basename "$logfile")
ARCHIVED_NAME="${ARCHIVE_DIR}${FILENAME}.${TIMESTAMP}.gz"
echo "Archiving and compressing $logfile to $ARCHIVED_NAME"
gzip < "$logfile" > "$ARCHIVED_NAME" && rm "$logfile"
if [ $? -ne 0 ]; then
echo "Error archiving $logfile"
fi
done
# Optional: Delete archives older than a certain period (e.g., 30 days)
# find "$ARCHIVE_DIR" -type f -name '*.gz' -mtime +30 -delete
echo "Log rotation complete."