31 July, 2007

HowTo synchronize directories

Sometimes it is necessary to synchronize data between desktop computer and notebook, PC and PocketPC, main and backup server or between directories within one system.
I wrote and use script to this.
This script synchronizes one directory with another.

E.g.: if you have directory "master" with these files:
master/file1.txt
master/file2.txt
master/dir1
master/dir1/file3.txt
master/dir1/file4.txt

and if you want to synchronize it with "slave" directory,
you may type this command:
./xqx_usync.sh master slave
After execution of this command, "slave" directory will contain all files from "master":
slave/dir1
slave/dir1/file3.txt
slave/dir1/file4.txt
slave/file1.txt
slave/file2.txt


At first thought, this action looks like copy, but if files in the "master" directory is changed, then after execution of this command again, all data in "slave" will be replaced with new data from "master" directory. Also, if you add new file to the "master" directory, it will be copied into "slave". This script wraps "rsync" command, that fast and high-performance.



xqx_usync.sh

#!/bin/bash

#This script synchronizes <master> and <slave> directories.

MASTER=$1/
SLAVE=$2/

echo -n Syncing $SLAVE with $MASTER...

if test -z "$MASTER" -o ! -e "$MASTER"; then
echo "Usage: usync <master directory> <slave directory>"
exit
fi

if test -z "$SLAVE"; then
SLAVE=.
fi

rsync --archive $MASTER $SLAVE
echo OK


This script is created with Ubuntu Linux.

2 comments:

Bart said...

Why the hell use this script if all it does is execute rsync???

Instead of typing
./xqx_usync.sh master slave

I could be typing
rsync -a master slave

which is actually less typing!

Xantorohara said...

Yes, of course. You are right.
But my article describes how rsync works. I prefer writing scripts instead of direct commands, because in the script I can set sequence of commands.