-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.sh
85 lines (63 loc) · 1.73 KB
/
sync.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/bin/bash
masterPid=-1
killed()
{
echo "Exiting..."
pkill -fn "ssh -TMNf -S $sshFile $host"
rm $syncFile
exit
}
# trap the kill signal
trap killed EXIT
# -d Run on debug mode
# -q Quiet mode
# check if the -d argument was given.
if [ `echo $* | grep -c "\-d"` -ne 0 ]
then
# set debug mode
set -x
fi
# save the current stdout file descriptor
exec 3>&1
# check if the -q argument was given.
if [ `echo $* | grep -c "\-q"` -ne 0 ]
then
# set quiet mode. i.e. print on /dev/null
exec 1>/dev/null
fi
# the name of the file used for keeping the time of the last sync
syncFile=/tmp/.lastSync$$
# the name of the file used to keep the ssh connection
sshFile=/tmp/syncMaster$$
# the source is the first paramenter
src=$1
# the destiny is the second parameter
dest=$2
# check if the destiny is a remote connection.
if [ `echo $dest | grep -c "@"` -ne 0 ]
then
# get only the user@host from the destiny
host=`echo $dest | sed -e 's/:.*//'`
# keep a master connection for faster slave connections
ssh -TMNf -S $sshFile $host
fi
# Do an initial sync.
rsync -e "ssh -S $sshFile" -Phravz $src $dest
# create the sync file
touch $syncFile
while true
do
# Look for changed files after last $syncFiles change.
# This will give us the number of files changed after the last sync.
changedNum=`find $src -cnewer $syncFile -type f | wc -l`
if [ $changedNum -ne 0 ] # if at least one file was changed
then
echo "Number of files changed: $changedNum"
# Do the sync
rsync -e "ssh -S $sshFile" -Phravz $src $dest
# touch the sync file to keep the last sync time
touch $syncFile
fi
# Sleep some time so we don't eat all resources
sleep 1
done