BASH

Find and Delete Old Files for Cleanup

Automate disk space management by creating a bash script to efficiently find and safely delete files older than a specified number of days in a given directory.

#!/bin/bash

# --- Configuration ---
TARGET_DIR="/path/to/cleanup/logs"
DAYS_OLD="+30" # Files older than 30 days

# --- Script Logic ---

# Check if TARGET_DIR exists
if [ ! -d "$TARGET_DIR" ]; then
  echo "Error: Target directory '$TARGET_DIR' does not exist."
  exit 1
fi

echo "Searching for files older than $(echo $DAYS_OLD | sed 's/+//') days in: $TARGET_DIR"

# Find files and print them before deleting (for safety)
find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -print

read -p "Do you want to delete these files? (y/N): " -n 1 -r
echo

if [[ $REPLY =~ ^[Yy]$ ]]; then
  echo "Deleting files..."
  # Use -delete for safety and efficiency. '-exec rm {} \;' is also an option.
  find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -delete
  if [ $? -eq 0 ]; then
    echo "Deletion complete."
  else
    echo "Error during file deletion."
    exit 1
  fi
else
  echo "Deletion aborted."
fi

exit 0
How it works: This bash script helps manage disk space by finding and deleting old files. It targets a specified directory and identifies regular files (`-type f`) last modified (`-mtime`) a certain number of days ago (`+30` for older than 30 days). For safety, it first lists the files that would be deleted and then prompts the user for confirmation before executing the `find ... -delete` command, which is an efficient way to remove matched files.

Need help integrating this into your project?

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

Hire DigitalCodeLabs