Incremental backup shell command script for linux files

Simple incremental backup script, after you use it, select some parts and record them for future reference

# 昨天对应的月份
n_mon=$(date -d -1day +%Y%m)
# 组合文件夹路径
path=/home/admin/"$n_mon"
# 昨天的0点作为增量备份起始时间,今日0点作为截止时间
s_date=$(date -d -1day +%Y-%m-%d)' 00:00:00'
e_date=$(date +%Y-%m-%d)' 00:00:00'

s_time=$(date -d "$s_date" +%s)
e_time=$(date -d "$e_date" +%s)

# 创建备份文件夹
today=$(date +%Y%m%d)
mon_path=/home/admin/bak/$n_mon
bak_path=$mon_path'/'$today
if [ ! -d "$mon_path" ]; then 
	mkdir -p $bak_path
else
	mkdir $bak_path
fi
echo '>>> 创建文件夹:'$bak_path
echo '>>> 开始备份文件。。。'
s_s=$(date +%s)
for file in `ls $path`; do
    file_path=$path'/'$file
	ctime=$(busybox stat -c %Y $file_path) 
	# 比对文件的修改时间
	if [ $ctime -ge $s_time ]&&[ $ctime -le $e_time ]; then
		cp $file_path $bak_path'/'$file
	fi
done
b_s=$(date +%s)
echo '>>> 文件备份完成!(耗时:'$(($b_s - $s_s))'s)'
echo '>>> 开始打包。。。'
tar -zcPf /home/admin/bak/$today-bak.tar.gz $bak_path
c_s=$(date +%s)
echo '>>> 打包完成!(耗时:'$(($c_s - $b_s))'s)'
echo '>>> 删除备份文件夹。。。'
rm -rf $bak_path
r_s=$(date +%s)
echo '>>> 删除完成!(耗时:'$(($r_s - $c_s))'s)'
echo '>>> 备份任务完成!(共耗时:'$(($r_s - $s_s))'s)'


Some problems in the script writing process, record them for fear of forgetting after a while:

1. When the script is running, the following problems are caused by the wrong format of the content of the script

$‘\r’: command not found for file in ls p a t h ‘ ; d o s y n t a x e r r o r n e a r u n e x p e c t e d t o k e n ‘ path`; do syntax error near unexpected token ` path;d osy n t a x error n e a r u n e x p ec t e d t o k e n ' 'do\
insert image description here
r'Solution:Use the npp editor, clickEdit > Document Format Conversion >Convert to Unix(LF)

2. The time stamp obtained in the script and the modification time of the file, the default is seconds, not milliseconds

Guess you like

Origin blog.csdn.net/qq_42049516/article/details/131224426