Monday, September 1, 2008

Linux - A Simple Backup Script

Taking backup periodically is one of the common task in Linux. Here let me get you thru' simple bash backup script.

Scenario: Under the user's home directory, 'repos' directory has all the repository underwhich the regular development goes on. As a repository might crash anytime, it is required to take back periodically datewise.

Assumption: Consider both 'backup' and 'repos' folder exists under the user's HOME directory

#------------backupscript--------------

mkdir ~/backup/`date +%d-%m-%Y`
for i in `ls ~/repos`
do
cp -r ~/repos/`echo $i` ~/backup/`date +%d-%m-%Y`/`echo $i`
#recursively copies the folder
done

#------------backupscript--------------

~ => represents the HOME directory of the user.
date +%d-%m-%Y => this command will create current system date in the format dd-mm-yyyy
`` => this takes the command and places the output of the command in place instead.

Step1: This script creates the current dated folder under the 'backup' folder exists in the user's HOME directory.
Step2: Takes all the directory and filenames exists under 'repos' folder exists in the user's HOME directory in the iteration variable i.
Step3: For each directory (or) file, the loop gets iterated.
Step4: Recursively copies the directory/file been took, under the current dated folder comes under backup folder from user's HOME directory.
Step5: Once all the directories/files copied, it's comes out of the loop. That's end of the script.

Save this script and give the executable permission to script. Now your backup script is ready.

$chmod u+x

Now it is the question how to schedule this script to run periodically. Let me get you through about cron scheduler in next blog.

--
Anand
anand.sadasivam@googlemail.com

No comments: