完 Cleaning your folders up

One of the greatest things about Linux is how easily you can automate it. It gives you a huge amount of flexibility and control over your system, and it allows you to offload all the mundane or repetitive tasks to the system.

In this guide, I’ll briefly show you how you can periodically clear old files and folders from a directory. I use this to clear down my downloads folder, but you could use it anywhere.

The first thing you need to do is find the directory in which you want to clear content from. In my case, that’s my downloads folder. On my system, that’s located at:

/home/myUsername/Downloads

If you want to get to your Downloads folder quickly, you can run cd $Home to go to your home folder. The Downloads folder should be in there.

When you’re in the folder you want to clear, type pwd to get the location of the folder. Keep note of this for later.

Next, you need to create a crontab entry to periodically clear the folder. To do this, you’ll need to open /etc/crontab in a text editor with sudo. My preferred editor is nano, so I would run sudo nano /etc/crontab

Once you’re in this file, you need to navigate to the bottom and then add this line:

@daily root find /YOUR/FOLDER/LOCATION* -mtime +DAYS -type f -delete

Make sure you replace /YOUR/FOLDER/LOCATION with the folder you want to use (make sure you don’t remove the *) and DAYS with the age of the files you want to delete in days (eg, if I entered 60, then any files over 60 days old would be deleted when this ran).

An example of this would be:

@daily root find /home/phil/Downloads* -mtime +30 -type f -delete

This would clear any files older than 30 days from Phil’s downloads folder, and it would check daily.

What this script does is:

  • Run once a day
  • Execute the command as root
  • Find the folder you specified
  • Find any files or folders within it that are older than the age you specified
  • Delete them

Note: Daily is actually midnight. If your computer isn’t usually turned on at midnight, you might want to replace @daily with @reboot. Doing this would mean that checking for and deleting old files would happen whenever you turn your computer on.

An example of this would be:

@reboot root find /home/phil/Downloads* -mtime +30 -type f -delete

Once you’re happy with everything, you can save the file. The file will be loaded automatically the next time you turn on your machine, but if you want to enable it immediately, you can run sudo service cron reload. Note that it should automatically detect the file changes anyway after a few moments, so you may not need to do anything to get it to start working.