C小加

厚德 博学 求真 至善 The bright moon and breeze
posts - 145, comments - 195, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

一天一个shell实例(3)定时备份文件

Posted on 2012-09-07 11:00 C小加 阅读(2310) 评论(1)  编辑 收藏 引用 所属分类: Linux

写一个备份文件的脚本,利用crontab定时执行。


步骤如下:

1,设置备份目的目录

2,进入目的目录

3,获取时间,设置备份文件名

4,备份文件


#!/bin/bash

DIRNAME
=`ls /root | grep bak`  #1

if [ -"$DIRNAME" ]  #2
then
mkdir 
/root/bak  #3
fi

cd 
/root/bak  #4

YY
=`date +%y`   #5
MM
=`date +%m`
DD
=`date +%d`
etc
=_etc

BACKETC
=$YY$MM$DD$etc.tar.gz  #6
tar 
-zcvf $BACKETC /etc  #7
echo 
"fileback finished!"

#1:获取root/bak字符串

#2:-z选项判断是否为空

#3:如果为空就创建目录

#4:进入该目录

#5:获取当前时间

#6:设置备份文件名

#7:将/etc目录下所有文件打包备份

         -z 用gizp压缩和解压缩文件,若加上此选项创建的压缩包,解压的时候也许要加上此选项

         -c 创建新的包

         -v 详细报告tar处理文件的信息

         -f 使用压缩文件或设备,该选项通常事必选的



定时执行脚本需要修改etc中的 crontab文件


root@Notebook-PC:/etc# vi crontab

/etc/crontab: system-wide crontab

# Unlike any other crontab you don
't have to run the `crontab'

# command to install the 
new version when you edit this file

# and files 
in /etc/cron.d. These files also have username fields,

# that none of the other crontabs 
do.

SHELL
=/bin/sh

PATH
=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command

17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly

25 6    * * *   root    test -/usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

47 6    * * 7   root    test -/usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )

52 6    1 * *   root    test -/usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

0 1   * * *   root    test4.sh           #加上此行,表示每天1时执行脚本        
#

* * * * * #表示每分钟

1 * * * * #表示每小时的第一分钟

2 12 * * * #表示每天的12:02

0-59/2 * * * * #每两分钟执行一次任务





Feedback

# re: 一天一个shell实例(3)定时备份文件  回复  更多评论   

2012-09-12 17:39 by SunRise_at
一天一个实例,该补好几个了。

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理