mongodb数据库在linux下定时进行备份与清除

来源:互联网 发布:淘宝买家4心要多少好评 编辑:程序博客网 时间:2024/05/17 06:35

linux下每天定时备份mongo,经过了一番折腾终于完成了


  1. 写shell脚本

1.1 定时备份

[plain] view plain copy
  1. #!/bin/bash  
  2. sourcepath='/app/mongodb-linux-x86_64-2.4.1'/bin  
  3. targetpath='/backup/mongobak'  
  4. nowtime=$(date +%Y%m%d)  
  5.    
  6. start()  
  7. {  
  8.   ${sourcepath}/mongodump --host 127.0.0.1 --port 27017 --out ${targetpath}/${nowtime}  
  9. }  
  10. execute()  
  11. {  
  12.   start  
  13.   if [ $? -eq 0 ]  
  14.   then  
  15.     echo "back successfully!"  
  16.   else  
  17.     echo "back failure!"  
  18.   fi  
  19. }  
  20.    
  21. if [ ! -d "${targetpath}/${nowtime}/" ]  
  22. then  
  23.  mkdir ${targetpath}/${nowtime}  
  24. fi  
  25. execute  
  26. echo "============== back end ${nowtime} =============="  
1.2 定时清除,保留7天的纪录

[plain] view plain copy
  1. #!/bin/bash  
  2. targetpath='/backup/mongobak'  
  3. nowtime=$(date -d '-7 days' "+%Y%m%d")  
  4. if [ -d "${targetpath}/${nowtime}/" ]  
  5. then  
  6.   rm -rf "${targetpath}/${nowtime}/"  
  7.   echo "=======${targetpath}/${nowtime}/===删除完毕=="  
  8. fi  
  9. echo "===$nowtime ==="  

以上代码参考:http://www.cnblogs.com/tangnie/p/3148782.html


写完以上shell,

对shell赋权(chmod +x mongobak.sh),


准备执行时,遇到了错误:

syntax error near unexpected token '

我很想跟踪下,看看shell执行的每一步都有什么结果,但不太懂shell,于是乎baidu,

还真找到一篇文章,顿时兴奋了,

http://jingyan.baidu.com/article/9f63fb91d014b8c8410f0e7a.html

看了上面的文章,觉得notepad++,居然还有这作用,点赞!!!


至此,shell的编写和执行完成了,工作完成了60%。


2. 写crontab表达式

2.1 执行crontab -e

2.2 按i键,进入编辑模式。

       写表达式

[plain] view plain copy
  1. 10 04 * * * /shell/mongobak 1>/log/crontab_mongo_back.file &  
  2. 10 02 * * * /shell/mongobakdelete 1>/log/crontab_mongo_delete.file &  

写完后,却不知如何保存并退出了,凭着以前的经验,

按了下ctrl+c,果然退出了编辑模式,又baidu,

http://www.linuxidc.com/Linux/2011-05/35644.htm


参考上面的文章,

又按了 :x,保存并退出了crontab   !!!


涉及到的知识很多啊,一波好几折。