BudiBadu Logo
Samplebadu

Bash by Example: Temp Cleaner

Bash 5.0+

Finding and deleting old files in a directory using the find command with time-based filters, implementing automated cleanup policies with -mtime for modification time, testing with -print before actual deletion with -delete, maintaining system cleanliness by removing temporary files, and implementing safe file deletion patterns with confirmation.

Code

#!/bin/bash

TEMP_DIR="temp_workspace"
DAYS_OLD=7

# Setup dummy data
mkdir -p "$TEMP_DIR"
touch "$TEMP_DIR/recent.txt"
touch -d "10 days ago" "$TEMP_DIR/old.txt"

echo "Cleaning $TEMP_DIR..."

# Find files modified more than N days ago
# -mtime +7 means "more than 7 days"
# -print shows them
echo "Found old files:"
find "$TEMP_DIR" -type f -mtime +$DAYS_OLD -print

# Delete them
# -exec rm {} \; runs rm on each file found
# Alternatively: -delete (if supported)
find "$TEMP_DIR" -type f -mtime +$DAYS_OLD -exec rm {} \;

echo "Cleanup complete."

# Verify
if [ -f "$TEMP_DIR/old.txt" ]; then
    echo "Error: old.txt should be gone."
else
    echo "Success: old.txt deleted."
fi

rm -rf "$TEMP_DIR"

Explanation

Temporary directories often accumulate junk files that are never cleaned up. Over time, this can waste inodes and disk space. This script uses the powerful find command to identify files based on their modification time and delete them automatically.

The core logic uses find path -mtime +N. The +N syntax is slightly counter-intuitive: it means "greater than N days". So +7 matches files modified 8 or more days ago. Conversely, -7 would match files modified less than 7 days ago (recent files).

To perform the deletion, we use the -exec action. The syntax -exec command {} ; tells find to run the specified command for every match, replacing {} with the filename. This is safer than piping to xargs if filenames contain spaces, although find ... -print0 | xargs -0 is the most robust method for handling strange filenames.

Code Breakdown

9
touch -d "10 days ago". This is a handy trick to simulate old files for testing scripts without waiting for actual time to pass.
22
-exec rm {} ;. The backslash escapes the semicolon, which is required to terminate the command. Without it, Bash would consume the semicolon.