How To Add A Cron Job

I was asked to write a script to delete images more than a day old from a directory, and to provide instructions on how to set this up as a cron job/cron task.

So this is step by step, assuming you have no knowledge of how to do it:

Create and Test the Script

Ssh into the machine using putty etc.

Become the user you want to run this as. if you want to run this as bitnami, ensure you are ssh’d in as bitnami.

In this case I am on an ubuntu flavored box provisioned by Bitnami in the AWS cloud.

To become root, type
sudo -s

( whichever user runs the script will need to have sufficient permission on the files concerned. )

Change to the users home directory, type:
cd ~

Create the new file, type:
touch delete-photos

Note: type touc ( I am deliberately omitting part of the command) -- hit the tab key for auto complete.

Next, make it executable, type:
chmod +x delete-photos

Edit the file, type:
nano delete-photos

Paste this into the file:

#! /bin/bash

# this will remove all .jpg files over a day old in this path

# all one line /usr/bin/find /tmp/images/uploaded/*.jpg -mtime +1 -exec /bin/rm -f {} \;

Note: use a right click to paste it in nano / putty. the last line is all one line.

Save and close nano:

type CTRL + X
hit the “Y” key
hit the enter key

Test the script

Type:
sh ~/delete-photos or
sh delete-photos

This assumes you are in the directory of the bash script.

or
./delete-photos

There is a period at the start.

To view the files in the folder type this:

ls -al /tmp/images/uploaded/

Install in Crontab

Start up crontab for nano, type:

VISUAL="nano -bw" crontab -e

Copy this text into memory then paste into crontab (right click):

# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 7) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *  command to be executed
1 1 * * * /root/delete-photos

Note: This means the script will run at one minute past 1am every day of the month, every month of the year and every day of the week.

If you used the bitnami user, replace the last line with this: 1 1 * * * /home/bitnami/delete-photos.

To save and close nano, type:
CTRL + X
hit the “Y” key
hit the enter key

All Done!

If you do not have nano, depending on your box, you may need to install it:

Centos: yum install nano

Ubuntu: apt-get install nano

If you noticed, I used:
/usr/bin/find and bin/rm in the script rather than just find or rm. This is good practice in a bash script. Use the command which find or which rm to locate the full path to the program you need to run.

To find out how to use the "find" command, type:
man find to see the manual on find.

Enjoy!