BASH

Auto-Cleanup Old Log Files

Implement a bash script to automatically delete log files older than a specified number of days, freeing up valuable disk space on your web server and preventing log bloat.

#!/bin/bash

# Configuration Variables
LOG_DIR="/var/log/your_app"
DAYS_TO_KEEP=30 # Number of days to retain log files
LOG_FILE_PATTERN="*.log" # Pattern for log files to clean up

echo "Starting log cleanup in $LOG_DIR..."

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

# Find and delete log files older than DAYS_TO_KEEP
# -type f: Only consider files
# -name "$LOG_FILE_PATTERN": Match files by pattern
# -mtime +$DAYS_TO_KEEP: Files modified more than DAYS_TO_KEEP days ago
# -exec rm -v {}: Execute 'rm -v' (verbose delete) on each found file
# {}: Placeholder for the found file
# \;: Terminates the -exec command

echo "Searching for files in '$LOG_DIR' matching '$LOG_FILE_PATTERN' older than $DAYS_TO_KEEP days..."

find "$LOG_DIR" -type f -name "$LOG_FILE_PATTERN" -mtime +$DAYS_TO_KEEP -print -exec rm {} \;

if [ $? -eq 0 ]; then
    echo "Log cleanup completed successfully."
else
    echo "WARNING: Log cleanup process encountered issues or no files were deleted."
fi

echo "Log cleanup script finished."
How it works: This script provides an automated solution for managing disk space by cleaning up old log files. It's configured with a target `LOG_DIR`, `DAYS_TO_KEEP` for retention, and a `LOG_FILE_PATTERN` (e.g., `*.log`). The core of the script uses the `find` command. It searches within the `LOG_DIR` for files (`-type f`) matching the specified pattern (`-name "*.log"`) that were last modified more than `DAYS_TO_KEEP` days ago (`-mtime +$DAYS_TO_KEEP`). For each file found, it executes `rm {} \;` to delete it. This script is excellent for scheduling with cron to prevent log files from consuming excessive disk space on web servers over time.

Need help integrating this into your project?

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

Hire DigitalCodeLabs