Cron Jobs to Delete Files after 'X' days

Cron Jobs to Delete Files after 'X' days

Table of contents

No heading

No headings in the article.

What are cron jobs?

The act of manually going through your files and deleting them can be very tedious. What if there was a simpler way to automate this process? Cue in cron jobs.

Cron is a utility program that lets users input commands for scheduling tasks repeatedly at a specific time. Tasks scheduled in cron are called cron jobs. Users can determine what kind of task they want to automate and when it should be executed. A cron file is a simple text file that contains commands to run periodically at a specific time. The default system cron table or crontab configuration file is /etc/crontab, located within the crontab directory /etc/cron.*/.

Basic Cron operations

This is not a class on cron jobs but it would be unfair for me not to mention some basic cron commands. Some of them are;

To create or edit a crontab file:

crontab -e

If no crontab files are found in your system, the command will automatically create a new one. crontab -e allows you to add, edit, and delete cron jobs. You'll need a text editor like vi or nano to edit a crontab file. When entering crontab -e for the first time, you'll be asked to choose which text editor you want to edit the file with.

To see a list of active scheduled tasks:

crontab -l

If your system has multiple users, you can view their crontab file lists by entering the following command as a superuser:

crontab -u username -l

You can also easily edit other users' scheduled jobs by typing the following crontab command:

sudo su crontab -u username -e

Lastly, to delete all scheduled tasks:

crontab -r

Alternatively, the following command is the same as crontab -r, except it will prompt the user with a yes/no option before removing the crontab:

crontab -i

In addition to crontab, the root user can also add cron jobs to the etc/cron.d directory. It's most suitable for running scripts for automatic installations and updates.

Example:

In this part, we'll create a cron job that deletes files in a particular folder that are older than a certain number of days;

  1. Create a bash script to locate the folder and delete the contents of the folder (todelete) that are older than 30 days:
find /var/log/todelete/ -type f -name '*.txt' -mtime +30 -exec rm {} \;
  1. Save the script and make it executable by all users using the command:
    chmod +x file.sh
    
  2. Create a cron job for the script and make it run every 1st of every month:
    crontab -e
    0 0 1 * * /home/file.sh
    
  3. Save and exit.

Conclusion

Setting up automatically scheduled jobs is a very practical solution that prevents you from forgetting important tasks and cron jobs are an excellent way for system administrators to manage repetitive tasks. I hope this article has given you a basic understanding of what cron jobs are and how they can be used to automate tasks. Happy learning :)