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

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)'

You should be able to delete all files older than 1 day in /home/username/directory and all directories below it with:

find /home/username/directory -type f -mtime +1 -delete

And to schedule that command every three hours set it as a cron job:

crontab -e

Then inside the crontab:

0 */3 * * * find /home/username/directory -type f -mtime +1 -delete

Which runs your command every three hours on the hour (i.e. minute 0), so 3:00 am, 6:00am etc.

Go the the cron and crontab manpages for more information on them.