Script to delete files from a Linux directory


This one's for anyone who's ever ignored a growing pile of log files—until it became a real problem.

In one of our environments, we had a shared directory where developers regularly dropped log and temp files. It was supposed to be cleaned up periodically, but (as often happens) that part was overlooked. For a while, nothing broke, so no one paid attention. We figured it wasn’t urgent.

Fast forward a year, and that same directory had ballooned to hundreds of thousands of files. What triggered alarms wasn’t disk space (though that was quickly becoming a concern)—it was how painfully slow it became to even look at the folder. A simple ls -ltr command took more than 3 minutes to respond, and sometimes it just sat there doing nothing. That’s when we realized this needed fixing now.

The Game Plan

The goal was simple: delete files older than a certain number of days (we picked 150 days). But we also wanted a quick and scalable way to do this without manually browsing or deleting files. We came up with a small Python script that executes a Linux find command to delete files older than a given age. To top it off, the script sends an email notification with the results—success or failure—so we know exactly what happened after each run.

This script isn’t fancy. It just works. It runs in the foreground, waits until the deletion is done, and then gives a nice little summary.

First, we changed the path in the DELETE_CMD line to point to the actual folder where our old log files were piling up. We also set it to delete files older than 150 days. You can change the number based on how far back you want to keep files.

Then, we updated the email section with real sender and recipient addresses. If you're using Gmail, you’ll need to use an app-specific password for it to work (don’t use your actual email password).

We tested the script by running it manually in the terminal to make sure it was deleting the right files and sending us an email after it finished.

Once we saw that it worked correctly, we set it to run automatically by adding it to a cron job. Now it cleans up the folder every month without us having to think about it.


import subprocess
import smtplib
from email.mime.text import MIMEText

# === CONFIG ===
DELETE_CMD = "find /your/target/folder -maxdepth 1 -type f -mtime +150 -print0 | xargs -0 -n 1000 -P 10 rm -f"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
FROM_EMAIL = "your_email@gmail.com"
FROM_PASSWORD = "your_app_password" # Use an app-specific password
TO_EMAIL = "recipient@example.com"
SUBJECT = "File Deletion Status Report"

# === Step 1: Run the deletion command and capture output ===
try:
result = subprocess.run(DELETE_CMD, shell=True, check=True, capture_output=True, text=True)
body = f" File deletion completed successfully.\n\nSTDOUT:\n{result.stdout or 'None'}"
except subprocess.CalledProcessError as e:
body = f" File deletion failed.\n\nReturn Code: {e.returncode}\nSTDERR:\n{e.stderr or 'None'}"

# === Step 2: Send email ===
msg = MIMEText(body)
msg["Subject"] = SUBJECT
msg["From"] = FROM_EMAIL
msg["To"] = TO_EMAIL

try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(FROM_EMAIL, FROM_PASSWORD)
server.send_message(msg)
print(" Status email sent.")
except Exception as e:
print(f" Failed to send email: {e}")



Comments