linux 编写mongodb备份脚本

原文地址:http://www.cnblogs.com/tangnie/p/3148782.html

Mongodb用的是可以热备份的mongodump和对应恢复的mongorestore,在linux下面使用shell脚本写的定时备份,代码如下

1.定时备份

#!/bin/bash
sourcepath='/app/mongodb-linux-x86_64-2.4.1'/bin
targetpath='/backup/mongobak'
nowtime=$(date +%Y%m%d)

start()
{
  ${sourcepath}/mongodump --host 127.0.0.1 --port 27017 --out ${targetpath}/${nowtime}
}
execute()
{
  start
  if [ $? -eq 0 ]
  then
    echo "back successfully!"
  else
    echo "back failure!"
  fi
}

if [ ! -d "${targetpath}/${nowtime}/" ]
then
 mkdir ${targetpath}/${nowtime}
fi
execute
echo "============== back end ${nowtime} =============="

2.定时清除,保留7天的纪录

#!/bin/bash
targetpath='/backup/mongobak'
nowtime=$(date -d '-7 days' "+%Y%m%d")
if [ -d "${targetpath}/${nowtime}/" ]
then
  rm -rf "${targetpath}/${nowtime}/"
  echo "=======${targetpath}/${nowtime}/===删除完毕=="
fi
echo "===$nowtime ==="