Backup your files using tar and cronjobs on Mac OS X

Posted by – August 25, 2010

Mac OS X comes with a huge amount of useful stuff. You just need to find and use them. Here is a walkthrough showing you how to set up an automatically backup-system on Mac OS X.

There are several ways to backup your files and probably the best way to do it would be to use rsync. It allows you to backup your files onto a remote machine. But probably this is a bit to heavy for the task you most probably want to achieve: Backup a folder on your local harddrive on a regular basis.

First, create a new file called in a folder of your choice. I place sh scripts in /User/myusername/Documents/scripts.

Open it in you favourite editor and type:

# Remove the oldest backup file.
rm –f /Library/WebServer/backups/backup.2.tgz

# Rename the old backup files
mv –f /Library/WebServer/backups/backup.1.tgz /Library/WebServer/backups/backup.2.tgz
mv –f /Library/WebServer/backups/backup.0.tgz /Library/WebServer/backups/backup.1.tgz

# create a new backup file.
tar –czf /Library/WebServer/backups/backup.0.tgz /Library/WebServer/Documents/*

Replace the directories to the directories of your choice. Note: The directory paths have to be absolute paths.

The above script will create a new compressed backup file named backup.0.tgz of my htdocs directory located at /Library/WebServer/Documents. A total of three backups will be found in /Library/WebServer/backups/, where backup.0.tgz is the latest and backup.2.tgz the oldest one.

To set up a new so called cronjob (a command that will be excecutet on a defined, regulare basis) open up your terminal and type:

crontab –e

This will open up your crontab file in your default editor. Probably vim. If you have no crontab file, it will simply create a new empty one.

After pressing i to insert into vim, type:

#min hour mday month wday command
0 3 * * 6 sh /Users/myusername/Documents/scripts/

Replace the file path with the path of your custom backup script. Press ESC to stop inserting and type :wq to write and quit vim. A new cronjob has been defined. It will be run at 3 am every Saturday.

You can define the time you want the script to be excecuted like this:

Minute Hour DayOfTheMonth Month Weekday (0 = Sunday, 6 = Saturday) Command

A few examples:

Daily excecution at 3:15 am

15 3 * * * command

Weekly excecution at 6:30 pm every Saturday

30 18 * * 6 command

Monthly excecution at midnight on the first day of the month:

0 0 1 * * command

Use */10 to define the excecution every 10 minutes:

*/10 * * * * command

Hope this helped you backup your files.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>