backup specially with shell script or python

需求: 备份目录,只备份新加的文件,不备份减少的文件

分析: 通常备份目录用 rsync 就可以达到目的,但开发同学怕误操作,删除文件,于是提出这个 只增不减 的需求

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
#!/bin/bash
backUp(){
local sourceDir=$1 #需要备份的文件/目录

local destDir=$2 #备份目的地

if [ -d "$sourceDir" ] #备份目录
then

#如果目录尚未备份,则创建此目录
if [ ! -d "$destDir/$sourceDir" ]
then
echo -e "创建目录\t$sourceDir"
mkdir -p "$destDir/$sourceDir"
fi

#对目录中对每一个文件,递归调用此函数进行备份
for var in $(ls "$sourceDir")
do
backUp "$sourceDir/$var" "$destDir"
done
else #备份文件
#如果文件在尚未备份,则直接复制
if [ ! -f "$destDir/$sourceDir" ]
then
echo -e "备份文件\t$sourceDir"
cp "$sourceDir" "$destDir/$sourceDir"
else

#如果文件已存在,则比较两个文件对最后修改时间,如果文件已修改,则更新文件
lastModifi_backup=$(date -r "$destDir/$sourceDir" +%s)
lastModifi_current=$(date -r "$sourceDir" +%s)
if [ "$lastModifi_current" -gt "$lastModifi_backup" ]
then
echo -e "更新文件\t$sourceDir"
cp "$sourceDir" "$destDir/$sourceDir"
fi
fi
fi
}
backUp "$1" "$2"

运行脚本: ./backupSpecially.sh "/date/originData" "/date/backup_dir"

发现运行shell脚本有问题,于是大神帮我写了个python

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
#!/usr/bin/env python2.7
# -*- encoding:utf-8 -*-
import os,time,filecmp

def differentFileCopy(sourcePath, targetPath):
if not os.path.exists(sourcePath):
return
if not os.path.exists(targetPath):
os.makedirs(targetPath)
for fileName in os.listdir(sourcePath):
absourcePath = os.path.join(sourcePath, fileName)
abstargetPath = os.path.join(targetPath, fileName)
if os.path.isdir(absourcePath):
if not os.path.exists(abstargetPath):
os.makedirs(abstargetPath)
differentFileCopy(absourcePath, abstargetPath)
if os.path.isfile(absourcePath):
if not os.path.exists(abstargetPath):
print 'copy %s to %s' %(fileName,abstargetPath)
os.system('cp'+' '+absourcePath+' '+targetPath)
if not filecmp.cmp(absourcePath,abstargetPath):
print 'copy %s to %s' %(fileName,abstargetPath)
os.system('cp'+' '+absourcePath+' '+targetPath)


if __name__ == '__main__':
startTime = time.clock()
sourcePath = r"/date/originData"
targetPath = r"/date/Data_backupDir"
differentFileCopy(sourcePath, targetPath)
endTime = time.clock()
time_mi = endTime // 60
time_s = endTime // 1 % 60
time_ms = ((endTime * 100) // 1) % 100
print("总用时:%02.0f:%02.0f:%2.0f" % (time_mi, time_s, time_ms))
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~