BASH
Cleaning Up Old Files and Directories
Automate the cleanup of stale build artifacts, cache files, or temporary directories by identifying and removing files older than a specified number of days.
#!/bin/bash
# Directory to clean up
TARGET_DIR="/path/to/your/builds_or_cache"
# Number of days old for files/directories to be considered for deletion
DAYS_OLD=7
# Dry run flag: set to 'true' to just list files, 'false' to delete
DRY_RUN=true
# --- Configuration End ---
echo "Starting cleanup script for directory: $TARGET_DIR"
echo "Files/directories older than $DAYS_OLD days will be targeted."
if [ ! -d "$TARGET_DIR" ]; then
echo "Error: Target directory '$TARGET_DIR' does not exist. Aborting."
exit 1
fi
if $DRY_RUN; then
echo "
--- DRY RUN: The following files/directories WOULD BE DELETED ---"
# Find files older than N days
find "$TARGET_DIR" -type f -mtime +$DAYS_OLD -print
# Find empty directories older than N days (to clean up residual empty folders)
# Note: -mtime only applies to regular files or directories, not contents.
# To delete empty directories, you usually combine it with -empty or separate find calls.
# For robustness, we delete files first, then empty directories.
find "$TARGET_DIR" -type d -empty -mtime +$DAYS_OLD -print
echo "
--- END DRY RUN ---"
echo "To perform actual deletion, set DRY_RUN=false in the script."
else
echo "
--- Performing actual deletion ---"
echo "Deleting files older than $DAYS_OLD days..."
find "$TARGET_DIR" -type f -mtime +$DAYS_OLD -print -delete
echo "Deleting empty directories older than $DAYS_OLD days..."
# Delete empty directories that were created more than N days ago
find "$TARGET_DIR" -type d -empty -mtime +$DAYS_OLD -print -delete
echo "Cleanup complete."
fi
exit 0
How it works: This script helps automate the process of cleaning up old or stale files and directories, which is crucial for maintaining disk space and project hygiene in web development environments. It targets a specified directory and identifies files and empty directories older than a configurable number of days. The script includes a `DRY_RUN` mode for safe testing, allowing you to preview what would be deleted before actual execution, thus preventing accidental data loss. This is especially useful for managing build artifacts, cache folders, or temporary uploads.