BASH

Delete Old Files and Directories by Age

Automatically clean up stale log files, temporary build artifacts, or cached data by deleting files and empty directories older than a specified number of days to free up space.

#!/bin/bash

# Directory to clean up
TARGET_DIR="/path/to/your/temp/files"

# Files and directories older than this many days will be deleted
DAYS_OLD=30

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

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

# Find and delete old files
# -type f: only files
# -mtime +$DAYS_OLD: modified more than DAYS_OLD ago
# -delete: delete the found items (be careful with this!)
find "$TARGET_DIR" -type f -mtime +$DAYS_OLD -delete

# Find and delete empty directories (after files have potentially been deleted)
# -type d: only directories
# -empty: only empty directories
# -delete: delete the found items
find "$TARGET_DIR" -type d -empty -delete

echo "Cleanup complete. Review the directory if necessary."
How it works: This script automates the cleanup of old files and empty directories within a specified `TARGET_DIR`. It uses the `find` command: first, it identifies and deletes files (`-type f`) that were last modified more than `DAYS_OLD` ago (`-mtime +$DAYS_OLD`). Afterward, it finds and deletes any directories (`-type d`) that have become empty (`-empty`) as a result of the file deletion, or were empty to begin with. This is ideal for managing logs, caches, or temporary build outputs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs