Bash Maintenance Nirvana

email-addthis printer-addthis favorites-addthis facebook-addthis digg-addthis | Share

18 Jun 2006 03:04:15
Category: Bash Programming

Yesterday I wrote a little bash script to take care of some maintenance on webGENEius.

I wanted a way to regularly backup my site files without doing if manually every time. My host provides through CPanel a backup feature. But I still have to remember to do it. I wanted to just "Set it and forget it." :p

So on the server I wrote a simple bash script to tar ball the home directory. In my home directory I created a directory named "bin" and a directory named "bups" (backups). And in the bin directory I placed this bash script and made it executable.

#!/bin/bash

#define the home path because we don't what user will execute cron. SPATH=/home/myuser
#set a variable holding the day month and year for naming the tar ball

TARDATE=`date +%d%m%y`
#first check to see if any backupxxx.tar exists and remove them if they do.

if [ -e $SPATH/bups/backup* ]; then
rm $SPATH/bups/backup*
#display a message if it is or is not removed
echo "backup.tar has been removed";
else echo "backup.tar not removed";
fi
#Paranoia check just to be sure they're gone for good
if [ ! -e $SPATH/bups/backup*.tar ]; then
#Tar ball the home directory and put it in "bups"
tar -cf $SPATH/bups/backup$TARDATE.tar $SPATH/*; fi
#mail me a completion message.
echo "Backup process complete" | mail -s "Backup log" my@emailaddress.org;

Then in CPanel I found cron and set it to run my script in /home/myfolder/bin/myscript at a time when I knew my home computer would be up and running.

So that's only half the process. We now have a tar ball containing everything in our home directory. Now I needed another script to go out and get the tar ball and then remove it.

#!/bin/bash
#Change directories on my local machine to where the download will end up cd /home/yourfolder/yourbackupfolder
ftp -in <
open yoursite.com user username password

cd bups

mget *.tar

mdelete *.tar

bye

EOF

Now on my local machine I changed cron to execute the script 15 minutes after the preceding script executed. And that's it.

Now I never have to think about whether my site files are backed-up. The only bad thing about this method is that you'll need your site files to total about half of your allotted storage space. The great thing about this method is you'll need *nix on your server and on your home machine!