Introduction
Log rotation helps keep log files from getting too big and uses less disk space. It also makes it easier to find recent logs.
#!/bin/bash LOG_DIR="/path/to/logs" MAX_SIZE=10485760 # 10 MB in bytes for LOG_FILE in "$LOG_DIR"/*.log; do if [ -f "$LOG_FILE" ]; then FILE_SIZE=$(stat -c%s "$LOG_FILE") if [ "$FILE_SIZE" -ge "$MAX_SIZE" ]; then mv "$LOG_FILE" "$LOG_FILE.$(date +%Y%m%d%H%M%S)" touch "$LOG_FILE" fi fi done
# Rotate logs larger than 5 MB LOG_DIR="/var/log/myapp" MAX_SIZE=5242880
mv "$LOG_FILE" "$LOG_FILE.$(date +%Y-%m-%d)"
touch "$LOG_FILE"#!/bin/bash LOG_DIR="./logs" MAX_SIZE=1024 # 1 KB for demo mkdir -p "$LOG_DIR" # Create a sample log file with some content LOG_FILE="$LOG_DIR/sample.log" echo "This is a test log line." > "$LOG_FILE" for i in {1..50}; do echo "Line $i" >> "$LOG_FILE"; done # Log rotation script for LOG_FILE in "$LOG_DIR"/*.log; do if [ -f "$LOG_FILE" ]; then FILE_SIZE=$(stat -c%s "$LOG_FILE") if [ "$FILE_SIZE" -ge "$MAX_SIZE" ]; then mv "$LOG_FILE" "$LOG_FILE.$(date +%Y%m%d%H%M%S)" touch "$LOG_FILE" echo "Rotated $LOG_FILE" else echo "$LOG_FILE size is under limit" fi fi done
log rotation script in bash?$(date +%Y-%m-%d) produces a safe filename format like 2024-06-01.gzip logfile-$(date +%Y-%m-%d).log ls logfile-*.log.gz | wc -l
wc -l command output if there are 3 compressed log files matching the pattern?gzip command compresses a log file, creating a file ending with .gz. The ls logfile-*.log.gz lists all compressed log files matching the pattern.ls outputs 3 lines. Piping to wc -l counts these lines, so output is 3.mv logfile.log logfile-$(date +%Y-%m-%d).log gzip logfile-$(date +%Y-%m-%d).log rm logfile.log
mv command renames logfile.log to logfile-date.log, so logfile.log no longer exists after this.rm commandrm logfile.log tries to delete a file that was already moved, causing an error or no effect.rm logfile.log command deletes the original log after moving, causing error -> Option Cls -1t lists files sorted by modification time, newest first. tail -n +6 outputs lines starting from line 6, i.e., files older than the 5 newest. xargs rm -f deletes those files.Pass the test and this pattern moves unknown