BASH

Automated Cleanup of Old Log Files

Implement a bash script to automatically delete log files older than a specified number of days, helping to manage disk space and maintain server hygiene.

#!/bin/bash
LOG_DIR="/var/log/nginx"
DAYS_TO_KEEP=30 # Keep logs for the last 30 days

if [ ! -d "$LOG_DIR" ]; then
    echo "Error: Log directory '$LOG_DIR' does not exist." >&2
    exit 1
fi

echo "Cleaning up logs in $LOG_DIR older than $DAYS_TO_KEEP days..."

# Use find to locate and delete files older than N days
# -type f: Only consider files
# -mtime +N: Files modified N*24 hours ago. +N means strictly greater than N days.
# -exec rm {} + : Deletes the found files efficiently
find "$LOG_DIR" -type f -name "*.log" -mtime +"$DAYS_TO_KEEP" -exec rm {} + 

if [ $? -eq 0 ]; then
    echo "Log cleanup completed successfully."
else
    echo "Log cleanup failed or encountered issues." >&2
    exit 1
fi

# Alternative using -delete (more efficient but older find versions might not support it)
# find "$LOG_DIR" -type f -name "*.log" -mtime +"$DAYS_TO_KEEP" -delete
How it works: This script automates the cleanup of old log files in a specified directory. It uses the `find` command to locate files (e.g., `*.log`) that were last modified more than a set number of days ago and then deletes them. This is a crucial task for server maintenance to prevent disk space exhaustion due to accumulating logs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs