脚本如下
#!/bin/bash
## 源目录项目名称,需根据目录名进行调整
project_name=/logs/alarm/
## 源目录
basedir=/opt/logs/$project_name
## 备份目录
backdir=/opt/back_logs/
## 定义readme文件 记录备份文件
rr=/opt/back_logs/readme
## 创建备份目录
if [ ! -e $backdir ];then
mkdir -p $backdir
fi
## 一个月前
to_date=`date -d "-1 month " +%Y-%m-%d`
## 源目录赋值变量
cd $basedir
for file in `ls $basedir`
do
## 截取日志属性时间值,按截取年月日创建目录,将源日志备份到对应时间的目录下
y=`echo $file | awk -F'-' '{printf "%s-%s-%s\n",$3,$4,$5}' | awk -F'.' '{print $1}' |awk -F '-' '{print $1}'`
m=`echo $file | awk -F'-' '{printf "%s-%s-%s\n",$3,$4,$5}' | awk -F'.' '{print $1}' |awk -F '-' '{print $2}'`
day=`echo $file | awk -F'-' '{printf "%s-%s-%s\n",$3,$4,$5}' | awk -F'.' '{print $1}' |awk -F '-' '{print $3}'`
#ls |cut -c16-25
## 一个月前
if [[ $y-$m-$day > $to_date ]];then break;fi
#echo $y-$m-$day $to_date
if [ ! -e $backdir$file ];then
tree $backdir >> $rr
mkdir -p $backdir/$y/$m/$day/$project_name/ &> /dev/null
cp $file $backdir/$y/$m/$day/$project_name/ &> /dev/null
sum=`ls $backdir/$y/$m/$day$project_name/ |wc -l` &> /dev/null
if [ $? -eq 0 ];then
echo -en "----- \t\t\t" >> $rr
echo `date` >> $rr
echo -en "----- \t\t\t" >> $rr
echo "$backdir$y/$m$project_name$day The backup OK" "Number of package $sum" >> $rr
else
echo -en "----- \t\t\t" >> $rr
echo `date` >> $rr
echo -en "----- \t\t\t" >> $rr
echo "$backdir$y/$m$project_name$day The backup NO" "Number of package $sum" >> $rr
fi
fi
done
## 备份日志上传到obs
/opt/case/obsutil/obsutil cp -r -f $backdir$y obs://obs-log-archive/data/ >> $rr 2>&1 && echo "数据上传到obs成功" >> $rr || echo "数据上传到obs失败" >> $rr
echo `date +%Y/%m/%d/%T` "script over!" >> $rr
演示创建对应的日志路径与日志名,用于脚本测试
# cd basedir && touch alarm-2021-09-{01..31}.{1..31}.log.tar标签:rr,##,backdir,区分,echo,awk,日志,备份,day From: https://blog.51cto.com/u_11410590/5739996