0

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

2 Answers 2

4

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:

filename04-04-2018.tar.gz
filename04-05-2018.tar.gz
filename04-06-2018.tar.gz
2
  • What does the "| xargs" mean?
    – Ramez Dous
    Apr 14, 2018 at 17:31
  • xargs takes the piped-in output and run it as an argument for rm :) Feb 5, 2021 at 19:54
4

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.

1
  • I don't get the fifth point!
    – Ramez Dous
    Apr 14, 2018 at 17:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .