实现准备# 需要备份文件路径:/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%S1.编写shell脚本[root@localhost tmp]# vi /opt/apollo/test.sh# 编译器# !/bin/bash# 日志备份到该目录下,定义变量使用单引号mypath=’/tmp/logs’# 回应/tmp/logsecho ${mypath}# 要备份的日志mylog=’/opt/apollo/logs/access_log’# 回应/opt/apollo/logs/access_logecho ${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.log2.执行test.sh[root@localhost apollo]# ./test.sh-bash: ./test.sh: Permission denied3.执行ls -la[root@localhost apollo]# ls -latotal 8drwxr-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.sh4.给文件test.sh赋与执行权限[root@localhost apollo]# chmod +x ./test.sh[root@localhost apollo]# ls -latotal 8drwxr-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.sh5.再次执行,脚本没有报错[root@localhost apollo]# ./test.sh/tmp/logs/opt/apollo/logs/access_log20190120080932/tmp/logs /tmp/logs/20190120080932_access.log6.编辑定时任务[root@localhost logs]# crontab -eno crontab for root - using an empty onecrontab: installing new crontab7.查看定时任务# 每分钟执行一次test.sh* * * * * sh /opt/apollo/test.sh8.重启crond[root@localhost logs]# service crond reloadRedirecting to /bin/systemctl reload crond.serviceYou have new mail in /var/spool/mail/root9.编写文件access_log# 需要备份文件路径:/opt/apollo/logs/access_log# 编辑文件[root@localhost logs]# vi /opt/apollo/logs/access_log# 追加内容如下:mmmmmmmmmmmmmmmmmmmmm10.过1分钟,再去查备份存放目录[root@localhost logs]# cat 20190120083101_access.logdjddjsjsjsjjsjsjsjmmmmmmmmmmmmmmmmmmmmm11.到此为止,定时备份任务完成.恭喜你,学会备份了!12.删除定时任务[root@localhost logs]# crontab -rYou have new mail in /var/spool/mail/root13.查看定时任务[root@localhost logs]# crontab -lno crontab for root