0

I need a cron job that will delete all files with these extensions (.jpg, .jpeg, .png, .pdf) in a folder (including files in subfolders, but not the subfolders themselves) twice a day. I'm using Dreamhost which allows you to customize the frequency within their UI, so I believe I just need the command.

Because the files can take a minute or two to get processed upon upload for extra safety it would be nice if the job only deleted files that were at least 5 minutes old, but that is optional.

Thank you so much for your help - I'm new to cron jobs!

timarion
  • 3
  • 1

1 Answers1

0
find <path> \( -name \*.jpg -o -name \*.jpeg -o -name \*.png -o -name \*.pdf \) -type f -mmin +5 -delete

For the explanation: man find.

Tomek
  • 3,390
  • 1
  • 16
  • 10
  • So for the path, would I use an absolute path like this? find /home/server_name/example.com/wp-content/uploads/forms \( -name \*.jpg -o -name \*.jpeg -o -name \*.png -o -name \*.pdf \) -type f -mmin +5 -delete – timarion Nov 17 '22 at 19:57
  • Yes. Consider testing this first, just drop `-delete` and examine the output. Please note backslashes are needed there (to escape shell metacharacters: `(`, `)` and `*`). – Tomek Nov 17 '22 at 20:00
  • Ok, so it finds all the relevant files in the path that I specify, but not files in subfolders - any way to get those found as well? – timarion Nov 17 '22 at 22:48
  • Ok, added an "*" at the end of the directory path, and it picked up the files in subdirectories. – timarion Nov 17 '22 at 23:21
  • That's a bit unexpected. Are you sure it is descending in all subdirectories? If not - try to drop `-type f` part from the command. – Tomek Nov 18 '22 at 13:11
  • Is this not expected? If there's a file in this directory: /home/server_name/example.com/wp-content/uploads/forms/test/test.png THEN /home/server_name/example.com/wp-content/uploads/forms/* will find it with the conditions we set above? However: /home/server_name/example.com/wp-content/uploads/forms/ will not. – timarion Nov 18 '22 at 16:16
  • `-type f` means files only. I guess this is why it dropped the first level subdirectories but I am not 100% sure. For me it is a bit unexpected but honestly I didn't test it and and didn't think a lot about it - so I may have missed something. If it works - use it, if it doesn't - dig into manual and improve it. – Tomek Nov 18 '22 at 17:05
  • Hmmm, I thought -f meant making it a foreground process. Anyways, thank you very much for all your help. I believe I have a workable solution now! – timarion Nov 18 '22 at 17:21