最近工作需要,写了一个shell脚本用来清理及备份动态业务数据表。表是以时间维度做的分区。脚本逻辑很简单,先扫mongodb库,得到所有的表名。之后遍历表名,筛选出过期的以及需要备份的。之后做删除和备份操作。注:中间用到了一个记录已经备份过的表的文件。
其中用到了很多小的细节点和命令语法。
sed 替换 例:sed 's/\"//g' 删除字符串中的双引号。sed 's/b/ppp/' 替换b为ppp
nowdate=$(date +%Y%m%d) 格式化当前时间
ago2date=$(date -d '1 days ago' +%Y%m%d) 格式化前一天的时间
adate=${x:0-8} 截取右侧后8个字符
if [ `grep -c "$x" /root/shell/back-xxx-new/bak-xxx-names` -eq 0 ] 条件语句必须用` 否则会报类型错误。
#定时 备份 mongodb表 名称特点 xxxx_1103_20180503
#!/bin/bash
#备份xxxx xxx_1101_20180509
re=$(/root/tools_package/mongodb/bin/mongo xx.xx.xx.xx:xxxx/xxxx -u xxxx -p xxxx --eval "db.getCollectionNames()" | grep "xxx" | sed 's/\"//g' | sed 's/\,//g')
nowdate=$(date +%Y%m%d)
ago2date=$(date -d '1 days ago' +%Y%m%d)
delcol=
bakcol=
arr=($re)
for x in ${arr[@]}; do
adate=${x:0-8}
#收集 需要删除的表
if [ $nowdate -ge $adate ]; then
delcol=${delcol}" "${x}
fi
#收集需要备份的表
if [ `grep -c "$x" /root/shell/back-xxx-new/bak-xxx-names` -eq 0 ]; then
bakcol=${bakcol}" "${x}
fi
done
#备份
bakarr=($bakcol)
for bakc in ${bakarr[@]}; do
echo $bakc
/root/tools_package/mongodb/bin/mongoexport --port xxxx --db xxxx --collection $bakc --username xxxxx --password xxxx --out /mnt/xxxx/$bakc.json
echo $bakc >> /root/shell/back-xxxx-new/bak-col-names
done
#删除 过期表
delcommand=
delarr=($delcol)
for del in ${delarr[@]}; do
#echo "db.getCollection('$del').drop()"
delcommand="db.getCollection('$del').drop();"${delcommand}
done
echo $delcommand
使用 crontab -e 添加一行 每天早上6点执行一次
0 6 * * * /root/shell/xxxx.sh