Linux centos下設置定時備份任務


實現准備

# 需要備份文件路徑:/opt/apollo/logs/access_log
[root@localhost opt]# cd apollo/
[root@localhost apollo]# tree
.
├── logs
│   └── access_log
└── test.sh
# 文件備份存放路徑:/tmp/logs
# 備份文件加上時間戳date + %Y%m%d%H%M%S

1.編寫shell腳本

[root@localhost tmp]# vi /opt/apollo/test.sh
# 編譯器
# !/bin/bash

# 日志備份到該目錄下,定義變量使用單引號
mypath='/tmp/logs'
# 回應/tmp/logs
echo ${mypath}

# 要備份的日志
mylog='/opt/apollo/logs/access_log'
# 回應/opt/apollo/logs/access_log
echo ${mylog}

# 時間戳,執行命令使用``,esc下面的
time=`date +%Y%m%d%H%M%S`
# 回應時間戳
echo ${time}

# 備份日志access_log到/tmp/logs路徑下
cp ${mylog} ${mypath}/${time}_access.log
# 回應
echo ${mypath} ${mypath}/${time}_access.log

2.執行test.sh

[root@localhost apollo]# ./test.sh
-bash: ./test.sh: Permission denied

3.執行ls -la

[root@localhost apollo]# ls -la
total 8
drwxr-xr-x   2 root root   21 Jan 20 08:00 .
drwxr-xr-x. 14 root root 4096 Jan 20 07:07 ..
-rw-r--r--   1 root root  489 Jan 20 08:00 test.sh

4.給文件test.sh賦與執行權限

[root@localhost apollo]# chmod +x ./test.sh
[root@localhost apollo]# ls -la
total 8
drwxr-xr-x   2 root root   21 Jan 20 08:00 .
drwxr-xr-x. 14 root root 4096 Jan 20 07:07 ..
-rwxr-xr-x   1 root root  489 Jan 20 08:00 test.sh

5.再次執行,腳本沒有報錯

[root@localhost apollo]# ./test.sh
/tmp/logs
/opt/apollo/logs/access_log
20190120080932
/tmp/logs /tmp/logs/20190120080932_access.log

6.編輯定時任務

[root@localhost logs]#  crontab -e
no crontab for root - using an empty one
crontab: installing new crontab

7.查看定時任務

# 每分鍾執行一次test.sh
* * * * * sh /opt/apollo/test.sh

8.重啟crond

[root@localhost logs]# service crond reload
Redirecting to /bin/systemctl reload crond.service
You have new mail in /var/spool/mail/root

9.編寫文件access_log

# 需要備份文件路徑:
/opt/apollo/logs/access_log
# 編輯文件
[root@localhost logs]# vi /opt/apollo/logs/access_log
# 追加內容如下:
mmmmmmmmmmmmmmmmmmmmm

10.過1分鍾,再去查備份存放目錄

[root@localhost logs]# cat 20190120083101_access.log
djddjsjsjsjjsjsjsj
mmmmmmmmmmmmmmmmmmmmm

11.到此為止,定時備份任務完成.

恭喜你,學會備份了!

12.刪除定時任務

[root@localhost logs]# crontab -r
You have new mail in /var/spool/mail/root

13.查看定時任務

[root@localhost logs]# crontab -l
no crontab for root


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM