BASH

Find and Delete Files Older Than N Days

Automate cleanup of old log files or temporary data. This bash script efficiently finds and removes files modified before a specified number of days, freeing up disk space.

#!/bin/bash

# Configuration
TARGET_DIR="/path/to/your/logs" # Specify the directory to clean
DAYS_OLD=30 # Files older than this many days will be deleted

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

echo "Searching for and deleting files older than $DAYS_OLD days in '$TARGET_DIR'..."

# Find and delete files:
# -type f: Only consider regular files
# -mtime +DAYS_OLD: Files modified more than DAYS_OLD (e.g., +30 means 31 days or more)
# -print: Print the path of each file found before deleting (for logging/debugging)
# -delete: Delete the found files
find "$TARGET_DIR" -type f -mtime +$DAYS_OLD -print -delete

# Check the exit status of the find command
if [ $? -eq 0 ]; then
  echo "Cleanup complete. Old files removed from '$TARGET_DIR'."
else
  echo "An error occurred during the cleanup process." >&2
fi
How it works: This bash script automates the cleanup of old files in a specified directory. It uses the `find` command with several options: `-type f` ensures only regular files are targeted, `-mtime +DAYS_OLD` filters files based on their last modification time (e.g., files modified more than 30 days ago), and `-delete` removes the identified files. The script includes a check for the target directory's existence and logs its actions, providing a robust solution for managing disk space by removing outdated data like logs or temporary files.

Need help integrating this into your project?

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

Hire DigitalCodeLabs