Howto Backup Apple Mail using Bash and Cron
June 18th, 2009, filed under GeneralBecause of a recent hard-drive failure on my MacBook I had to replace my hard-drive and restore most of my data. Luckily I’ve been using my own automated backup script for Apple Mail which makes restoring a simple breeze.
I’m using a simple combination of bash and cron that automatically backups all my e-mail into one local .zip file. The local .zip file is automatically copied to my USB flashdrive the moment it’s connected to my laptop.
The bash script
Here’s the code for the bash script backup.sh that I’m using:
d1="/Users/Robert/Library/Mail/"
d2="/Users/Robert/Library/Mail Downloads/"
zip -ru /Users/Robert/Documents/Backup/Mail.zip "$d1" "$d2"
echo "Backup has finished!"
Make sure that the above bash script is executable (chmod +x) and has the correct paths to your own directories.

Example of the bash script shown with the Vim text editor
Cron
Cron is a time-based job scheduler in Unix-like computer operating systems such as Mac OS X. Cron is used to execute the above backup script at a specified time.
Using the terminal you can specify a cron job by using crontab -e and list current cron jobs with crontab -l. When done adding a new cron job you can exit by typing : followd by wq [enter]. This is how I’ve set up mine:
0,30 * * * * sh /Users/Robert/.scripts/backup.sh > /dev/null 2>&1
This will execute the backup script the 0th and 30th minute of every hour (and every day).
Backup on USB connect
Having all my e-mail backupped into one single .zip file on the local hard-drive is making the backup still vulnerable for hard-drive failures. Therefore I’m using an automated backup script that copies all my backup files to a USB flashdrive the moment it is connected to my MacBook.
Open the AppleScript with the Script Editor on your Mac and modify the locations to your own backup directory and (USB) backup drive. Save the script and place it in your user account at ~/Library/Scripts/Folder Action Scripts/.
Start Finder by pressing “Command + Shift + G” and go to the folder /Volumes. Right click in the directory, select “Attach a Folder Action” and select the Applescript.
Have your say
You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>