BASH

Automate Log File Cleanup and Rotation

Implement a simple Bash script to automatically remove old log files from a specified directory, helping to optimize server disk space and prevent log accumulation.

#!/bin/bash

# Configuration variables
LOG_DIR="/var/log/nginx" # Directory containing log files
DAYS_TO_KEEP=7          # Number of days to keep log files
LOG_FILE_PATTERN="*.log" # Pattern for log files (e.g., *.log, access.log.*)

# Check if the log directory exists
if [ ! -d "$LOG_DIR" ]; then
  echo "Error: Log directory '$LOG_DIR' not found." >&2
  exit 1
fi

# Find and delete old log files
find "$LOG_DIR" -type f -name "$LOG_FILE_PATTERN" -mtime +"$DAYS_TO_KEEP" -print -delete

echo "Cleanup complete. Old log files in $LOG_DIR (older than $DAYS_TO_KEEP days) have been removed."
How it works: This script helps manage disk space by automatically deleting old log files. It uses the `find` command to locate files within a specified `LOG_DIR` that match a `LOG_FILE_PATTERN`. The `-type f` option ensures only regular files are targeted. The `-mtime +DAYS_TO_KEEP` condition selects files that were last modified more than `DAYS_TO_KEEP` days ago. The `-print` option shows which files are being deleted, and `-delete` performs the deletion. This script is ideal for a daily cron job to keep log directories tidy.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs