BASH

Automated Cleanup of Old Files by Age

Automate the cleanup of old log files, cache files, or temporary directories by deleting files older than a specified number of days, helping manage disk space on web servers.

#!/bin/bash

# Usage: ./cleanup_old_files.sh /var/log/mywebapp 30
# Deletes files in specified directory older than N days.
# IMPORTANT: Use with caution!

TARGET_DIR="$1"
DAYS_OLD="$2"
DRY_RUN="${3:-true}" # Set to 'false' to actually delete files

if [ -z "$TARGET_DIR" ] || [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Target directory not specified or does not exist."
    echo "Usage: $0 <target_directory> <days_old> [dry_run=true|false]"
    echo "Example (dry run): $0 /var/log/mywebapp 30 true"
    echo "Example (actual delete): $0 /var/log/mywebapp 7 false"
    exit 1
fi

if ! [[ "$DAYS_OLD" =~ ^[0-9]+$ ]]; then
    echo "Error: Days old must be a positive integer."
    exit 1
fi

echo "--- Initiating Cleanup Script ---"
echo "Target Directory: $TARGET_DIR"
echo "Files older than: $DAYS_OLD days"
echo "Dry Run: $DRY_RUN"

if [ "$DRY_RUN" = "true" ]; then
    echo "Performing a DRY RUN. No files will be deleted."
    echo "Files that WOULD BE deleted:"
    find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -print
    echo "--- Dry Run Complete ---"
else
    read -p "WARNING: This will PERMANENTLY DELETE files. Are you sure you want to proceed? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "Proceeding with actual deletion..."
        find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -delete
        echo "Cleanup complete. Old files deleted."
    else
        echo "Aborted by user."
    fi
fi
How it works: This script helps web developers manage disk space by automatically identifying and deleting old files within a specified directory. It takes a target directory and a number of days. Files older than this age will be targeted for deletion. It includes a crucial "dry run" mode to preview which files would be deleted before actual deletion, and requires user confirmation for irreversible operations, making it safe for server maintenance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs