BASH

Finding and Deleting Old Files by Age

A simple yet powerful bash script to locate and safely remove files or directories older than a specified duration, ideal for cleaning up temporary files or old caches.

#!/bin/bash

TARGET_DIR="/path/to/my/cache" # Directory to clean up
DAYS_OLD=7                   # Files older than 7 days will be deleted
DRY_RUN=true                 # Set to 'false' to actually delete files

echo "--- Cleaning up old files in '$TARGET_DIR' ---"
echo "------------------------------------------------"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Directory '$TARGET_DIR' does not exist."
    exit 1
fi

echo "Looking for files older than $DAYS_OLD days..."

if [ "$DRY_RUN" = true ]; then
    echo "DRY RUN: Files that WOULD be deleted:"
    find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -print
    echo "Set DRY_RUN=false to enable actual deletion."
else
    echo "DELETING files older than $DAYS_OLD days..."
    # -type f : Only files
    # -mtime +N : Files modified N*24 hours ago
    # -delete : Delete files immediately (use with caution!)
    find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -delete
    echo "Cleanup complete."
fi

echo "------------------------------------------------"
How it works: This script is designed to clean up old files in a specified directory. It uses the `find` command with `-type f` to target only regular files and `-mtime +DAYS_OLD` to select files modified more than a certain number of days ago. A `DRY_RUN` variable allows testing which files would be deleted before actually executing the removal. When `DRY_RUN` is `false`, the `-delete` action is used to remove the identified files, providing a safe way to manage disk space for temporary files or caches.

Need help integrating this into your project?

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

Hire DigitalCodeLabs