Linux Shell脚本以交互方式同步目录
时间:2020-03-05 15:31:47 来源:igfitidea点击:
该脚本将在两个服务器之间同步两个目录。
基本上,我们使用rsync功能来运行该程序。
脚本将以交互方式请求输入以下详细信息。
1)远程服务器名称或者ip
2)远程系统用户名
3)要同步的本地目录
4)要同步到的远程目录
5)检查用户是否需要复制时间戳并保留权限
脚本同步目录
#Tell with shell to use
#!/bin/bash
#Ask user to enter remote server ip or name
while [[ -z ${RS} ]]
do
echo -n "Remote syncing server ip/name: "
#Save input into variable with name RS
read RS
done
#Ask user to enter remote server user
while [[ -z ${RU} ]]
do
echo -n "Remote syncing server user: "
#Save input into variable with name RU
read RU
done
#Ask user if copy timestamp and preserve permissions, valid input is Yes or No, will ask until valid input
while [[ "$TS" != "Yes" && "$TS" != "No" ]]
do
echo -n "Copying with timestamp and preserve permissions : Yes/No "
#Save input into variable with name TS
read TS
done
#If user need to copy timestamp and preserve permissions we need to use key -p additionally.
if [ "$TS" = "Yes" ]
then
TS=" -p "
else
#If no need to copy timestamp and preserve permissions, we don't need to use any additional key
TS=""
fi
#Ask user to enter local directory to sync, also check if directory exist
while [[ -z ${LD} || !( -d ${LD}) ]]
do
echo -n "Syncing local directory location: "
#Save input into variable with name LD
read LD
done
#Ask user to enter remote directory
while [[ -z ${RD} ]]
do
echo -n "Remote Syncing directory location: "
#Save input into variable with name RD
read RD
done
echo -n "Syncing ..."
#Run sync with presented parameters
rsync -r $TS ${LD} ${RU}@${RS}:${RD} --progress
脚本输出
#./sync.sh Remote syncing server ip/name: node246.theitroad.com Remote syncing server user: linuser Copying with timestamp and preserve permissions : Yes/No Yes Syncing local directory location: /home/theitroad/backup/database01 Remote Syncing directory location: /storage/backup/ Syncing … sending incremental file list CSR/file 1,120 100% 410.16kB/s 0:00:00 (xfr#1, to-chk=8/10) CSR/file1 1,110 100% 1.06MB/s 0:00:00 (xfr#2, to-chk=7/10) CSR/file2 1,675 100% 1.60MB/s 0:00:00 (xfr#3, to-chk=6/10) CSR/file3 2,479 100% 2.36MB/s 0:00:00 (xfr#4, to-chk=5/10) CSR/201406/file4 1,110 100% 1.06MB/s 0:00:00 (xfr#5, to-chk=3/10) CSR/201406/file5 1,679 100% 1.60MB/s 0:00:00 (xfr#6, to-chk=2/10) CSR/201406/file6 1,115 100% 1.06MB/s 0:00:00 (xfr#7, to-chk=1/10)

