Create a new Cron Job

The Scenario:

A folder on my Ubuntu file server (/home/baxter/backups) stores nightly backups (tar files). With each file approximately 600mb the folder quickly become excessively large.

The Problem:

I have to remember to manually delete the files before the disk runs out of space.

The Solution:

Create a Cron Job (Linux scheduled task) that will run every day at 8am and which will delete any files older than 30 days.

Step 1: Create a script to search for and delete files over 30 days old

As this script will run as the root user it needs to be created in the root user home location (/root).
Create a new directory for the scripts to reside:
# mkdir scripts

Navigate to this folder and create a new blank file called purge.sh
# vim purge.sh

Add the following text and save the file (:wq):

#!/bin/bash
find /home/baxter/backups/* -mtime +30 -exec rm -f {} \;

The above text finds all (*) the files in the stipulated location that have a modified time (mtime) of 30 days ago. If there are any then forcibly remove (rm -f) them.

Make the script executable:
# chmod +x purge.sh

Step 2: Create a new cron job to run this script every day at 8am

Never manually configure the /etc/crontab file but run the following command:
# crontab -e

no crontab for root – using an empty one
crontab: installing new crontab

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use ‘*’ in these fields (for ‘any’).#
# Notice that tasks will be started based on the cron’s system
# daemon’s notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
0 8 * * * /root/scripts/purge.sh

Save the changes (wq)

NB If you’re confused on how to set the cron schedule, this great little link will help you.

Step 3: (Optional) Manually run the script to test it

Type ./purge.sh (within the /root/scripts/ directory) and press enter

 

Disclaimer: provided “AS IS” with no warranties and confer no rights

Advertisements