BASH

Find and Delete Old Files by Age and Extension

Recursively locate and remove files older than a specified number of days, filtered by file extension, to help manage disk space on web servers.

#!/bin/bash

TARGET_DIR="/var/www/logs"
FILE_EXTENSION="log"
DAYS_OLD=30 # Delete files older than 30 days

# Check if the target directory exists
if [ ! -d "$TARGET_DIR" ]; then
  echo "Error: Directory $TARGET_DIR not found."
  exit 1
fi

echo "Searching for files older than $DAYS_OLD days with extension .$FILE_EXTENSION in $TARGET_DIR..."

# Use find to locate files and -delete to remove them
# -type f: Only files
# -name "*.$FILE_EXTENSION": Match files with the specified extension
# -mtime +$DAYS_OLD: Files whose data was last modified N*24 hours ago. +N means more than N days.
# -print: Print the name of the file (useful for dry runs or logging)
# -delete: Delete the found files (use with caution!)

# Dry run first (optional, comment out 'echo' and uncomment '-delete' for actual removal)
find "$TARGET_DIR" -type f -name "*.$FILE_EXTENSION" -mtime +$DAYS_OLD -print

# To actually delete, uncomment the line below and comment out the -print line
# find "$TARGET_DIR" -type f -name "*.$FILE_EXTENSION" -mtime +$DAYS_OLD -delete

echo "Process complete. Please review the output above or uncomment the -delete line for actual removal."
How it works: This script uses the `find` command to locate files within a specified directory that are older than a set number of days and match a given file extension. It prints the paths of the found files, providing a "dry run" for review. Users can then uncomment the `-delete` option to perform the actual removal of these old files, aiding in disk space management and preventing accumulation of stale data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs