linux下shell脚本备份⽂件
以下是shell⾃动备份⽤的:
主要功能:
1)将pathSrc⽬录中的⽂件拷贝到pathDst⽬录中去。
  具体步骤:先查询源⽬录和⽬标⽬录中的⽂件,分别存在fileSrc和fileDst中。 -> 来两个循环,⽐较。不在fileDst的就拷贝过去。再判断⼀下是否拷贝成功。
2)将pathSrc中的⽂件保留180天。
  具体步骤:先查出源⽬录中⼤于180天的⽂件(就是那句find),然后删除。 
#!/bin/bash
v_time=`date"+%Y-%m-%d %H:%M:%S"`
bakstr="[Start auto backup gitlab data:]"${v_time}
logfile="/home/localgitlab/test/"
echo >> $logfile
echo $bakstr >> $logfile
pathSrc="/home/localgitlab/disk_new/backup"
filesSrc=$(ls $pathSrc)
pathDst="/media/localgitlab/a1df1b08-ae43-45ea-8067-994497738cb2/backups"
filesDst=$(ls $pathDst)
nSrcFileCount=0
### Backup file: The file that determines the original path is not in the target path,
### and is not copied.
for filename in $filesSrc
do
nSrcFileCount=$(( $nSrcFileCount + 1 ))
need_copy="yes"
for dstfile in $filesDst
do
if [ $filename == $dstfile ];then
need_copy="no"
fi
done
if [ $need_copy == 'yes' ];then
echo $filename " need backup" >> $logfile
strCompletePath=${pathSrc}'/'${filename}
cp $strCompletePath $pathDst
if [ $? -eq 0 ]; then
echo"copy file success" >> $logfile
else
echo"copy file fail" >> $logfile
fi
else
echo $filename " not need backup" >> $logfile
fi
done
echo"Src dir have file count:" $nSrcFileCount >> $logfile
### Keep only data within 180 days
delSrc=$(find $pathSrc -type f -mtime +180)
for delfilename in $delSrc
do
echo"Need delete file: " $delfilename >> $logfile
rm -f $delfilename
if [ $? -eq 0 ]; then
echo"delete file success" >> $logfile
else
echo"delete file fail" >> $logfile
fi
linux执行shell命令
done
补充:
1、有需要的话可以⽤crontab假如到⾃动运⾏中去。如果涉及到源⽬录和⽬标⽬录访问权限的问题,可能需要⽤root加⼊crontab。
1)crontab -l:列出所有⾃动运⾏的脚本
2)crontab -e:将要执⾏的脚本假如到⾃动运⾏中去
2、关于find命令:
find pathname -options [-print -exec -ok]
pathname    find命令所查的⽬录路径。
-print      find命令将匹配的⽂件输出到标准输出。
-exec      find命令对匹配的⽂件执⾏该参数所给出的shell命令。
-
ok 和- exec的作⽤相同,只不过以⼀种更为安全的模式来执⾏该参数所给出的shell命令,在执⾏每⼀个命令之前,都会给出提⽰,让⽤户来确定是否执⾏.
1. -name  按照⽂件名查⽂件
2. -perm  按照⽂件权限来查⽂件
3. -mtime -n +n  按照⽂件的更改时间来查⽂件,-n表⽰⽂件更改时间距现在n天以内,+n表⽰⽂件更改时间距现在n天以前。
4. -newer file1  查更改时间⽐⽂件file1新的⽂件。
5. -type  查某⼀类型的⽂件
b - 块设备⽂件。
d - ⽬录。
c - 字符设备⽂件。
p - 管道⽂件。
l - 符号链接⽂件。
f - 普通⽂件。
6. 使⽤-size选项 ,按⽂件的⼤⼩查⽂件的