BASH
Find and Delete Old Files Recursively
Learn to use the `find` command with various options to locate and safely remove files older than a specified number of days from a directory and its subdirectories.
#!/bin/bash
# --- Configuration ---
TARGET_DIR="/path/to/your/logs" # Directory to search in
DAYS_OLD="+30" # Files older than 30 days
# --- Safety Check ---
if [ -z "$TARGET_DIR" ] || [ ! -d "$TARGET_DIR" ]; then
echo "Error: TARGET_DIR is not set or does not exist: $TARGET_DIR"
exit 1
fi
echo "Searching for files older than $DAYS_OLD days in $TARGET_DIR..."
echo "These files will be listed first, then deleted."
echo "----------------------------------------------------"
# --- Dry Run (list files without deleting) ---
find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -print
echo "----------------------------------------------------"
read -p "Do you want to PROCEED with deletion? (y/N): " CONFIRM
if [[ ! "$CONFIRM" =~ ^[yY]$ ]]; then
echo "Deletion cancelled."
exit 0
fi
echo "Proceeding with deletion..."
# --- Delete Old Files ---
# Using -delete is often more efficient than -exec rm {} \;
# Ensure you are absolutely sure about the TARGET_DIR and DAYS_OLD
# as this command is irreversible.
find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -delete
if [ $? -eq 0 ]; then
echo "Successfully deleted old files."
else
echo "An error occurred during file deletion."
fi
echo "Script finished."
How it works: This script safely finds and deletes old files. It first configures a `TARGET_DIR` and `DAYS_OLD` threshold. A crucial safety check verifies the target directory's existence. The script then performs a dry run using `find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -print` to list files matching the criteria, allowing user confirmation before actual deletion. Upon confirmation, `find` is executed again, but this time with the `-delete` action, which efficiently removes the identified files. `find -type f` ensures only files are considered, and `-mtime +N` matches files modified N days ago or longer.