Monday, July 11, 2011

tar oneliner: backup to a network location

tar is a pretty straightforward and handy tool that anyone administering anything on a *nix box should learn. If I don't have a typo, the below one liner will create a system backup, excluding the named directories and send it via SSH to a remote server, where the .tar file will be written. Errors are redirected ( 2> ) to a log file in /var/log/backups (assuming you have this directory and it has the appropriate permissions.
One last note: if you don't run this as root, you won't get a complete (if any) archive created.

Command (the line break is only formatting on here. This command can be entered on one line.
tar cvpj --exclude=/dev/* --exclude=/sys/* --exclude=/tmp/* / 2> /var/log/backups/`date +%d%M%Y`_Backup.log | ssh yourserver "cat > /home/backups/`date +%d%M%Y`_Backup.tar"

c - create backup tar
v - list files being tarred
p - maintain file perms
j - use bzip2 (slower but deeper compression) / can use z instead which is gzip
g - could be added to this string of commands in order to create incremental backups
--exclude=   exclude some directory. The trailing * will stop tar from creating an empty copy of the excluded directory.
ssh - should be self-explanatory

To schedule this, you can use at or create a new cron entry such as:
10 * * * 1,3,5 /usr/bin/backup
were /usr/bin/backup is a script containing the above tar command and the command should run at 12:10 am on Monday, Wednesday, and Friday (days 1, 3, and 5 of the week)