gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
Write a shell script that rotates log files daily and should keep a maximum of seven…
- User
Write a shell script that rotates log files daily and should keep a maximum of seven days’ worth of logs and compress the older logs
- Assistant
Here is a sample shell script that rotates log files daily, keeps a maximum of seven days' worth of logs, and compresses the older logs:
#!/bin/bash LOG_DIR="/var/log/mylogs" LOG_PREFIX="mylog" MAX_DAYS=7 # Create log directory if it doesn't exist mkdir -p "$LOG_DIR" # Rotate log files daily current_date=$(date +"%Y%m%d") new_log_file="$LOG_DIR/$LOG_PREFIX-$current_date.log" mv "$LOG_DIR/$LOG_PREFIX.log" "$new_log_file" # Compress older log files find "$LOG_DIR" -name "$LOG_PREFIX-*.log" -mtime +$MAX_DAYS -exec gzip {} \; # Delete logs older than MAX_DAYS find "$LOG_DIR" -name "$LOG_PREFIX-*.log.gz" -mtime +$MAX_DAYS -deleteYou can save this script to a file (e.g., rotate_logs.sh), make it executable with
chmod +x rotate_logs.sh, and then set up a cron job to run it daily usingcrontab -e:0 0 * * * /path/to/rotate_logs.shThis cron job will run the script daily at midnight to rotate, compress, and delete old log files according to the specified retention policy.