I have a cron job that runs at midnight to delete all .txt files in a folder that are older than 7 days. I can see the job is running, but the files still exist in the folder.

I'm new to cron, so I'd really appreciate someone pointing out where I've gone wrong, or how to diagnose it if not obvious.

Here's my code with the directories obscured:

0 0 * * * bin/find /var/www/example.com/wp-content/targetdir -name "*.txt" -type f -mtime +7 -exec rm -rf {} \;

Thanks in advance all.

  • Can you add the output of the complete command when you run it in your terminal directly? Also, you should check the path to the find binary with 'which find' to make sure it's right as it seems it's missing a '/'
    – Val F.
    Jan 8, 2019 at 3:21
  • 1
    Is that path a typo? Jan 8, 2019 at 4:09

2 Answers 2

  • simply use 'find' or use the absolute path starting with / (for ubuntu it is /usr/bin/find)
  • if you want to delete files, do not use 'rm -r'

This one works fine:

0 0 * * * /usr/bin/find /var/www/example.com/wp-content/targetdir -name "*.txt" -type f -mtime +7 -exec rm -f {} \;
  • Thanks heiko. Am I right that I can leave 'usr' as it is, or do I need to replace that with the name of the user I'm logged in as (which is root)?
    – Oli
    Jan 10, 2019 at 2:45
  • see help.ubuntu.com/community/LinuxFilesystemTreeOverview - /usr/ is a default linux path... type "which find" to see the location of the find command on your system!
    – heiko
    Jan 10, 2019 at 8:37
  • Any reasons why you wouldn't use -delete? Jan 8, 2022 at 11:37
  • Will /usr/bin/find /var/www/example.com/wp-content/targetdir -name "*.txt" -type f -mtime +7 -execdir rm -f {} \; give the same result? Jan 8, 2022 at 12:00

Or even more simple:0 0 * * * /usr/bin/find /var/www/example.com/wp-content/targetdir -name "*.txt" -type f -mtime +7 -delete

Explained in:man find, ACTIONS -delete

  • Welcome on the ServerFault! I suggest to give more details, what is your config doing and how.
    – peterh
    Nov 26, 2020 at 13:09
  • Thanks for your answer. A explanation and some details would be very helpful.
    – bjoster
    Nov 30, 2020 at 14:38
  • @HvdW Can you please explain the advantages of using -delete over rm? Found many answers on the internet, but none of them satisfactory. Also is there any downside to using delete? An example would do Jan 8, 2022 at 11:36
  • -delete is just simpler, you don't have to fight with quoting and escape characters. Oct 26, 2023 at 11:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .