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"?


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.

| improve this answer | |
  • I don't get the fifth point! – Ramez Dous Apr 14 '18 at 17:33

I use one to delete backups older than 10 days and it looks something like this:

50 17 * * * find /path/to/files/filename* -type f -mtime +10 | xargs rm

I use filename* because they are for backups so they would look like this:

| improve this answer | |
  • What does the "| xargs" mean? – Ramez Dous Apr 14 '18 at 17:31

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.