You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux:定时删除嵌套目录中过期一周的PDF文件(仅删文件)

How to Automatically Delete Expired PDF Files with Cron

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):

  1. Open your user’s crontab editor:
crontab -e
  1. 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
  1. Save and exit the editor (in nano, that’s Ctrl+O, Enter, then Ctrl+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 root or 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 find command without -delete first 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:05:18