Introduction:
This bash script rotates log files to prevent them from growing too large over time. It archives the old logs, compresses them, and creates fresh log files for continued logging.
Instructions:
Run these commands to utilize the log rotator:
Example Output:
This bash script rotates log files to prevent them from growing too large over time. It archives the old logs, compresses them, and creates fresh log files for continued logging.
Bash:
#!/bin/bash
LOG_DIR="/var/log/myapp"
ARCHIVE_DIR="$LOG_DIR/archive"
# Create archive directory if it does not exist
mkdir -p $ARCHIVE_DIR
# Find and rotate log files
for file in $LOG_DIR/*.log; do
if [ -f "$file" ]; then
base=$(basename $file)
mv $file $ARCHIVE_DIR/${base}_$(date +%Y%m%d).log
# Optional: compress the rotated log
gzip $ARCHIVE_DIR/${base}_$(date +%Y%m%d).log
fi
done
# Recreate empty log files
for file in $ARCHIVE_DIR/*.gz; do
touch $LOG_DIR/$(basename $file .log.gz).log
done
echo "Log rotation complete."
Instructions:
Run these commands to utilize the log rotator:
Code:
chmod +x log_rotate.sh
sudo ./log_rotate.sh
Example Output:
Code:
Log rotation complete.