Posted on 2012-09-07 11:00
C小加 閱讀(2351)
評論(1) 編輯 收藏 引用 所屬分類:
Linux
寫一個備份文件的腳本,利用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 * * * * #每兩分鐘執行一次任務