Ubuntu – How to create a cron job that automatically delete files that are older than 30 days

crondelete

I'm using Ubuntu 14 desktop. I use this machine to backup other machines and as an FTP server for the security cameras.

I need to create a cron job that automatically deletes files that are older than 30 days. I did some search and I think I found the right command but I want to make sure I'm not missing something before executing it.

* 4 * * * find /home/USER/DIRECTORY1/DIRECTORY2/ -mindepth 1 -type f -mtime 29 -delete

Do I need to put "sudo" at the before the find command?

Do I need to put "+" before the number of days "29"?

Best Answer

First, put your find ... command in a bash script, and call that script from your crontab. If you have an encrypted home directory (cat /home/.ecryptfs/$USER/.ecryptfs/Private.mnt) you'll have to store your script outside your $HOME directory tree. Keeping a command in crontab makes configuring, logging and debugging harder, and the crontab command parser isn't as clever as bash's.

Second, always, Always, ALWAYS test find with -print, and get it to work, before considering -delete.

Third, the find test "-mtime 29" is telling find "Find the file's mtime, and return True if it's equal to 29. You should use -mtime +29, which find sees as "more than 29", which is what you want. From man find:

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

Fourth, be sure you have Write access to the directories in /home/USER/DIRECTORY1/DIRECTORY2/.

Fifth, do you mean /home/USER/DIRECTORY1/DIRECTORY2/ or /home/$USER/DIRECTORY1/DIRECTORY2/? If $USER is for the user's userid, you have a problem: cron doesn't define $USER in the runtime enviroinment. It does define $HOME, so you could use $HOME/DIRECTORY1/DIRECTORY2.

Related Question