BASH
Automate Deletion of Old Files
Learn to write a Bash script that efficiently finds and deletes files older than a specified number of days, perfect for log rotation or temporary file cleanup.
#!/bin/bash
# Directory to clean up
TARGET_DIR="/var/log/app_logs"
# Number of days after which to delete files
DAYS_OLD="+30"
# Ensure the directory exists
if [ ! -d "$TARGET_DIR" ]; then
echo "Error: Directory $TARGET_DIR does not exist."
exit 1
fi
echo "Searching for files older than $DAYS_OLD days in $TARGET_DIR..."
# Find and delete files older than N days
# -type f: Only consider regular files
# -mtime +N: Files last modified N*24 hours ago
# -exec rm {} \;: Execute rm command for each found file
find "$TARGET_DIR" -type f -mtime "$DAYS_OLD" -exec rm {} \;
if [ $? -eq 0 ]; then
echo "Old files successfully removed from $TARGET_DIR."
else
echo "Error: Failed to remove old files."
fi
How it works: This script uses the `find` command to locate and delete files within a specified directory that are older than a given number of days. It specifically targets regular files (`-type f`) and uses `-mtime +N` to identify files modified more than N days ago. The `-exec rm {} \;` part executes the `rm` command on each found file, making it ideal for managing log files, temporary assets, or old build artifacts to free up disk space.