BASH

Find and Delete Old Files by Age and Type

A bash script to locate and safely remove old files (e.g., logs, backups, temporary files) older than a specified number of days in a given directory.

#!/bin/bash

TARGET_DIR="/var/log/app"
DAYS_OLD=30 # Files older than this will be deleted
FILE_TYPE="log" # e.g., "log", "bak", "*" for all

echo "Searching for files older than $DAYS_OLD days in $TARGET_DIR with type .$FILE_TYPE..."

# Use -print0 and xargs -0 for safety with unusual filenames
# Add -delete instead of xargs rm for simpler find versions, but xargs is often preferred.
find "$TARGET_DIR" -type f -name "*.${FILE_TYPE}" -mtime +"$DAYS_OLD" -print0 | xargs -0 rm -v

echo "Cleanup complete."
How it works: This script is designed for system maintenance, specifically for cleaning up old files. It uses the `find` command to locate files within a `TARGET_DIR` that match a specific `FILE_TYPE` (e.g., `.log` files) and are older than `DAYS_OLD` (e.g., 30 days). The `-print0` option with `find` and `xargs -0` with `rm -v` are used together for safe handling of filenames containing spaces or special characters, preventing issues during deletion. This helps in maintaining disk space, especially for log files, temporary data, or old backups, by automating their removal.

Need help integrating this into your project?

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

Hire DigitalCodeLabs