Cron job to delete all files older than 7 days with extension in a specific folder - not working

Solution 1:

  • 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 {} \;

Solution 2:

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