Ubuntu – How to make the system delete all the files in a certain directory older than a certain time while keeping the directory structure intact

automationdeletedirectoryfilesscripts

I have a directory on my machine, think of it as my own sort of tmp directory, but it's in my ~ directory. And I want to make it so that my system every 3 hours deletes all the files in (though keeping any directory structure intact, but still deleting all the files in all the levels of the directories recursively) that directory which are older than a day.

I am running Ubuntu GNOME 15.10 with GNOME 3.18, can this be done? And if so, how? I would like this to be fully automated with no users interaction needed. This should be something automatically started when I login, so I shouldn't need to run something on every startup.

Best Answer

Using find:

find ~/tmp -type f -mtime +0 -delete
  • ~/tmp is the directory to be searched recursively, change this accordingly

  • -type f will look for only files

  • -mtime +0 which will match a file if it was last modified one day or more ago

  • -delete will just remove the matched file(s)

Here the catch is -mtime +0, most might think of using -mtime +1 but find will ignore any fractional time while calculating days. So, -mtime +1 will match a file if the last modification was made at least 2 days ago.

Quoting man find, -mtime has the same timing convention as -atime:

-atime n

File was last accessed n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.

Also note that if you want precision, you should look at the -mmin option of find to indicate time in minutes.

To run it periodically after 3 hours, you can add a cron entry.

Run crontab -e and add:

00 */3 * * * /usr/bin/find ~/tmp -type f -mtime +0 -delete

Using zsh to remove the files:

rm ~/tmp/**/*(.-m+0)

Adding to cron:

00 */3 * * * /usr/bin/zsh -c 'rm ~/tmp/**/*(.-m+0)'