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

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

步骤如下:

1,设置备份目的目录

2,进入目的目录

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

4,备份文件

#!/bin/bash

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

if [ -z "$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 -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

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

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

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

* * * * * #表示每分钟

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

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

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

原文地址:https://www.cnblogs.com/xingmeng/p/3030300.html