2

I'm currently using this cron job to delete stalled temp files in a particular location. How can I improve this to only delete files older than x days (e.g., 30 days)?

0 4 * * 0 /bin/rm -fv /home/*/tmp/Cpanel_*

6

You can use find:

find /home/*/tmp/Cpanel_*' -type f \! -newermt "month ago" -delete

find can be tricky, so do your homework reading about it and test well. The common practice is to test with a command that doesn't act on found targets, like ls or echo. find has some builtin commands you can use for testing. So you can start with this:

 find /home/*/tmp/Cpanel_*' -type f \! -newermt "month ago" -ls
  • 1
    Good answer. For more efficiency you could use the fact that find can have any number of directories or files before the first option, as in: find /home/*/tmp/Cpanel_* !-newermt "month ago" -delete; you can add -maxdepth 0 to ensure that only the files from the shell expansion are deleted, without descending any directories (probably not relevant here). – AFH Jun 17 '18 at 14:00
  • I am getting this message: -bash: !-newermt: event not found any idea what it means? – IMB Jun 17 '18 at 19:11
  • @IMB It means you are using Bash and it can't find the entry in its history. You don't need Bash. Use find as the command. – Tomasz Jun 17 '18 at 19:13
  • @IMB Or maybe not... There needs to be a break between ! and -. See updated line above. – Tomasz Jun 17 '18 at 19:15
  • @IMB And in fact it should be \! -newrmt. – Tomasz Jun 17 '18 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.