My first Cron Job

5 11 2008

So it’s been a little over a month since I’ve posted anything, and that’s cause I’ve been kind of busy with school, and therefore haven’t done much with the server. I did install phpBB3, but I didn’t think that was really worth a mention.

What I just got done doing is writing my first shell script and assigning it as a daily cron job. Basically what the job does is run through my Pictures directory–which I linked to at /var/www/Pictures/–and places an instance of the file from the “Image Thumbnails” post in each of the subdirectories. I did this because I found it annoying to have to constantly check the Pictures directory to see if anyone uploaded any new pictures, and then having to place the file in there myself. So, what the script does is run through all the directory’s contents and if it finds a directory it changes into that directory and copies a file called noindex.php from the maindirectory into a file called index.php in the directory it’s in. It then changes back out and continues the process until the entire contents of the folder is processed. Here’s the script, and a sample output.

#Script Name:
#Author Name: Willem Ellis
#Date: Tues Nov 4 17:22:00 CST 2008
#Description: This is a file used to insert
# index.php into newly created
# sub-directories within a main
# directory.
cd /var/www/Pictures/
for f in $FILES
if [ -d "$f" ]
echo "Processing $f..."
chmod 777 "$f"
cd "$f"
cat "../noindex.php" > index.php
cd ..
elif [ ! -d "$f" ]
echo "Not a directory..."

Processing Folder1…
Not a directory…
Processing Folder2…

This site is where I got a small part of this script, it explains what the for loop does. Basically it stores the list of files within the directory as the variable FILES. The for loop scrolls through the loop and saves each individual item in the list as f and works with each item one at a time until all the items have been processed. It’s saying for the variable f in the list FILES do the following… Then my if else if loop just says if the file you are on (f) is a directory change into it and copy noindex.php to index.php inside the directory. Otherwise if (elif) the file is not a directory, print out “Not a directory…” Each time the for loop completes, it moves to the next item and stores that as f until there’s nothing left in the list, at which point the script is done.

After I wrote the script, all I did was save the script as in /etc/cron.daily/ and edited /etc/crontab to run the job every day at 6:00PM.

00 17 * * * root /etc/cron.daily/

Hope someone else finds this handy.