BASH
Delete Old Files or Directories by Age
Automate the efficient cleanup of old files or empty directories within a specified path based on their age using `find`, perfect for managing logs, caches, and temporary data.
#!/bin/bash
TARGET_DIR="/path/to/your/logs"
DAYS_OLD=30
DRY_RUN=true # Set to false to actually delete
# Ensure the target directory exists
if [ ! -d "$TARGET_DIR" ]; then
echo "Error: Target directory $TARGET_DIR does not exist."
exit 1
fi
echo "Searching for files/directories older than $DAYS_OLD days in $TARGET_DIR"
if [ "$DRY_RUN" = true ]; then
echo "This is a DRY RUN. No files will be deleted. To enable deletion, set DRY_RUN=false."
# Find files older than N days
find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -print
# Find empty directories older than N days (optional, use with caution)
# find "$TARGET_DIR" -type d -empty -mtime +"$DAYS_OLD" -print
else
echo "Deleting files/directories older than $DAYS_OLD days in $TARGET_DIR"
# Find and delete files older than N days
find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -delete
# Find and delete empty directories older than N days
# find "$TARGET_DIR" -type d -empty -mtime +"$DAYS_OLD" -delete
echo "Deletion complete."
fi
How it works: This script uses the `find` command to locate and optionally delete files or empty directories older than a specified number of days within a target directory. It includes a `DRY_RUN` option for safe testing before actual deletion, making it a powerful tool for automated cleanup of logs, temporary files, or cached assets to free up disk space.