This article is over two years old. Life moves quickly, and thus there is a good chance any references, recommendations, or opinions in this content are out of date. Make sure to verify any information independently.

Simple Backup Script for Linux Servers

PublishedDecember 25 2010

I administer a local development server. I use it to practice my Unix terminal kung-fu, as well as develop some local intranet web applications. I’ve learned a lot from the old box. I’ve written a small bash script that I use to generate a backup of certain directories and compress it as a tarball.

The Code

Let’s start off with the final source code…

```bash THE_DATE=`date "+%Y-%m-%d"` cd /var/backups mkdir $THE_DATE cd $THE_DATE tar cvzf latest_backup.tar.gz -C / var/www home/alex etc usr/bin ```

Pre-run checks

First, make sure there is a directory /var/backups. It doesn’t matter if it already exists, just as long as it’s there. Also, make sure you can run this program as root.

Setting it up

Make a new file in /usr/bin, name it whatever you want (I call mine wwwbackup). The content of that file is the source code above.

Save the file, then on the command line, run this command:

sudo chmod +x /usr/bin/yourfilename

That command will make the file executable by the system.


The only line you’re going to want to change is the last line. At the end there are a few directory paths, these are the directories to be included in the backup. Each directory is separated by a space. Make sure you leave the first / and the space after it.

For example, if I wanted to only backup /var/www the last line would read:

tar cvzf latest_backup.tar.gz -C / var/www

Running It

You can run the program by typing sudo wwwbackup (where wwwbackup is the name of your file).

If all goes well, you’ll see a list of all the files in the directories you set backing up. The script will create a folder with the current day’s date and place a tarball under that folder with your backup contents.

If you don’t want the script to list all of the files it’s backing up, remove the letter v from the last line. So it would start like: tar czf.