BASH

Automatically Remove Old Files and Directories

Use a Bash script to automatically find and delete files or empty directories older than a specified duration, ideal for routine cleanup of logs, cache, or temporary data.

#!/bin/bash
# Script to clean up old files and empty directories

TARGET_DIR="/var/log/app" # Specify the directory to clean
DAYS_OLD="+30"             # Files/dirs older than 30 days will be removed

echo "Cleaning up files and empty directories in $TARGET_DIR older than $DAYS_OLD days..."

# Delete old files
echo "Deleting old files..."
find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -exec rm {} \; -print
if [ $? -eq 0 ]; then
    echo "Old files deleted successfully."
else
    echo "Error deleting old files."
fi

# Delete empty directories (after files are removed, some might become empty)
echo "Deleting empty directories..."
find "$TARGET_DIR" -type d -empty -delete -print
if [ $? -eq 0 ]; then
    echo "Empty directories deleted successfully."
else
    echo "Error deleting empty directories."
fi

echo "Cleanup complete."
How it works: This script uses the `find` command to locate and delete files and empty directories within a `TARGET_DIR` that are older than `DAYS_OLD` specified. `-type f` targets files, `-type d` targets directories, `-mtime +N` specifies modification time, and `-delete` (or `-exec rm {} \;`) performs the deletion. It's crucial to test this script in a safe environment first.

Need help integrating this into your project?

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

Hire DigitalCodeLabs