← Back to all snippets
BASH

Find and Delete Old Files in a Directory

Reclaim valuable disk space by automatically locating and removing files older than a specified number of days in a target directory. Useful for cleaning up temporary files or old backups.

#!/bin/bash
TARGET_DIR=$1
DAYS_OLD=${2:-30} # Default to 30 days if not provided

if [ -z "$TARGET_DIR" ]; then
    echo "Usage: $0 <target_directory> [days_old]"
    echo "Example: $0 /var/www/uploads 7"
    exit 1
}

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

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

if [ "$DAYS_OLD" -le 0 ]; then
    echo "Error: Days old must be greater than zero."
    exit 1
fi

echo "Searching for files older than $DAYS_OLD days in '$TARGET_DIR'..."
# Using -print0 and xargs -0 for safety with filenames containing spaces or special characters
find "$TARGET_DIR" -type f -mtime +"$DAYS_OLD" -print0 | xargs -0 rm -v

if [ $? -eq 0 ]; then
    echo "Old files deleted successfully."
else
    echo "No old files found or an error occurred during deletion."
fi
How it works: This script helps manage disk space by finding and deleting old files. It takes a target directory and an optional number of days (defaulting to 30) as arguments. It uses the `find` command with `-mtime` to locate regular files (`-type f`) that haven't been modified for more than the specified days. It then safely pipes these filenames to `xargs -0 rm -v` for deletion, handling filenames with special characters correctly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs