Linux:定时删除嵌套目录中过期一周的PDF文件(仅删文件)
First, let’s break down what you need: a recursive search for PDF files older than 7 days in your users directory structure, delete only those files (leave directories intact), and schedule this to run automatically via cron.
Step 1: Test the File Deletion Command
Before setting up cron, always test the command manually to ensure it targets the right files. Run this in your terminal:
find /full/path/to/users -type f -name "*.pdf" -mtime +7
This will list all PDF files modified more than 7 days ago (the +7 means "older than 7 days"). Verify the list is correct—once you’re confident, add the -delete flag to actually remove them:
find /full/path/to/users -type f -name "*.pdf" -mtime +7 -delete
Let’s break down each part:
/full/path/to/users: Replace this with the absolute path to your top-level users directory (critical for cron, since it doesn’t use your shell’s working directory).-type f: Ensures we only target files (not directories).-name "*.pdf": Filters for only PDF files.-mtime +7: Selects files modified more than 7 days ago.-delete: Removes the matched files (only use this after testing!).
Step 2: Set Up the Cron Task
To schedule this to run regularly (e.g., daily at 2 AM, when server load is low):
- Open your user’s crontab editor:
crontab -e
- Add the following line to the end of the file:
0 2 * * * find /full/path/to/users -type f -name "*.pdf" -mtime +7 -delete
Let’s explain the cron schedule:
0: Minute (0 minutes past the hour)2: Hour (2 AM, using 24-hour format)*: Every day of the month*: Every month*: Every day of the week
- Save and exit the editor (in nano, that’s
Ctrl+O,Enter, thenCtrl+X). Cron will automatically apply the new schedule.
Important Notes
- Permissions: Ensure the user running the cron task has write access to all the PDF files you want to delete. If you’re using a system cron job (instead of a user crontab), you might need to run it as
rootor adjust file permissions accordingly. - Log Output: If you want to log what’s deleted (for debugging), modify the cron line to redirect output to a log file:
0 2 * * * find /full/path/to/users -type f -name "*.pdf" -mtime +7 -delete >> /var/log/pdf_cleanup.log 2>&1 - Dry Run First: Always run the
findcommand without-deletefirst to avoid accidentally removing the wrong files.
That’s it! This setup will automatically clean up old PDFs every day while leaving your directory structure untouched.
内容的提问来源于stack exchange,提问作者Robert Moritz

