Home » Questions » Computers [ Ask a new question ]

How do I compress a directory on a Unix web server and email it on a sheduled basis?

How do I compress a directory on a Unix web server and email it on a sheduled basis?

After hearing about various high profile website creators getting stiffed recently after hardware failures on their servers I would like to implement a backup strategy on my websites.

Asked by: Guest | Views: 64
Total answers/comments: 1
Guest [Entry]

"To start you off the commands you want to learn how to use; tar, mail and basic shell scripting.

The Shell Script

A really quick and dirty example of how to do this would be the following:

#! /bin/sh

# The following command creates a GZIP'd version of your folder. -c = create
# -z = use gzip, -f = file name of backup file
# You can use j instead of z to use bzip2. It's slightly slower but compresses
# more. Beware that images, videos and such do not compress well.
cd /PATH/NOT/IN/HOME/FOLDER; tar czf backup.tgz /PATH/TO/HOME/FOLDER

# If you only have access to your home folder you can modify the command to
# look like so, regular expressions are your friend here.
tar czf backup.tgz FOLDER1 FOLDER2 FILE3

# The mail program may be disabled and uses the local SMTP server so depending
# on your mail setup it may never even get to your inbox because it is flagged
# as unverified mail (Spam). For example, Gmail or a domain not hosted on that
# same server will almost most certainly not work. If this fails to work you
# can create a PHP or Python script that actually allows you to set the SMTP
# server. An alternative is to have this script echo some output and have cron
# send the output to you instead. It's dependent on your setup.
# -s Subject
#
mail -s ""Backup Done!"" ""youremailaddress@wherever.com""

Set the script to executable (chmod 755 nameOfScript.sh) and make note of where you've saved it on your

Getting Crontab to run the Shell Script

To set up your crontab from the command line enter crontab -e to edit your crontab file. The layout of the file is as below:

* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)

Source of Diagram: Admin's Choice

In this case, adding a line such as:

33 0 * * * /PATH/TO/HOME/FOLDER/nameOfScript.sh

will run the script every day at 0:33 / 12:33 AM.

If you want to find out more check out the man pages for tar, mail and crontab. They're indispensable when dealing with UNIX administration in any form. With uuencode you could even email the whole site to yourself if it was small enough."