编写shell脚本。
(写完需要wq保存退出,w保存,q退出,!强制)
[root@lmx var]# vi /var/test.sh
# 编译器
# !/bin/bash
# 日志备份到该目录下,定义变量使用单引号
mypath='/tmp/logs'
# 回应/tmp/logs
echo ${mypath}
# 要备份的日志文件夹
mylog='/var/log/tomcat'
# 回应/var/log/tomcat
echo ${mylog}
# 时间戳,执行命令使用``,esc下面的
time=`date +%Y%m%d%H%M%S`
# 回应时间戳
echo ${time}
# 备份日志文件tomcat到/tmp/logs路径下
cp -r ${mylog} ${mypath}/${time}_access.log
# 回应
echo ${mypath} ${mypath}/${time}_access.log
备份文件夹时用的cp -r ,如果备份单个文件时需要去掉 -r 在mylog中的路径也要改成你想要备份的文件名称,而不是一个文件夹。
给test.sh添加执行权限
[root@lmx var]# chmod +x ./test.sh
执行脚本
执行成功!
添加定时任务
1.安装crontabs服务并且设置开机自启:
yum install crontabs
systemctl enable crond
systemctl start crond
执行成功
2 编辑定时任务
vi /etc/crontab
分钟(0-59) 小时(0-23) 日(1-31) 月(1-12) 星期(0-6,0表示周日) 用户名 要执行的命令
分钟:0-59
小时:0-23
日期:0-31
月份:0-12
星期:0-6(0表示周日)
*: 表示任何时刻
,: 表示分割
-:表示一个时间段
/n : 表示每个n的单位执行一次。*/1, 就表示每隔1个小时执行一次命令。
如: 每隔30分钟重启系统
*/30 * * * root reboot
我这里设置每三秒执行一次/var 目录下的test.sh脚本,
crontab -e #进入编辑
*/1 * * * * /var/test.sh
查看定时任务
crontab -l
去文件夹中查看定时任务执行效果
[root@lmx ~]# cd /tmp/logs/
[root@lmx logs]# ls -la
drwxr-x---. 2 root root 4096 9月 18 10:17 20220918101706_access.log
drwxr-x---. 2 root root 4096 9月 18 10:27 20220918102702_access.log
drwxr-x---. 2 root root 4096 9月 18 10:28 20220918102801_access.log
drwxr-x---. 2 root root 4096 9月 18 10:29 20220918102901_access.log
drwxr-x---. 2 root root 4096 9月 18 10:30 20220918103001_access.log
drwxr-x---. 2 root root 4096 9月 18 10:31 20220918103101_access.log
drwxr-x---. 2 root root 4096 9月 18 10:32 20220918103201_access.log
drwxr-x---. 2 root root 4096 9月 18 10:33 20220918103301_access.log
drwxr-x---. 2 root root 4096 9月 18 10:34 20220918103401_access.log
drwxr-x---. 2 root root 4096 9月 18 10:35 20220918103501_access.log
drwxr-x---. 2 root root 4096 9月 18 10:36 20220918103601_access.log
drwxr-x---. 2 root root 4096 9月 18 10:37 20220918103701_access.log
drwxr-x---. 2 root root 4096 9月 18 10:38 20220918103801_access.log
drwxr-x---. 2 root root 4096 9月 18 10:39 20220918103901_access.log
drwxr-x---. 2 root root 4096 9月 18 10:40 20220918104001_access.log
drwxr-x---. 2 root root 4096 9月 18 10:41 20220918104101_access.log
drwxr-x---. 2 root root 4096 9月 18 10:42 20220918104201_access.log
drwxr-x---. 2 root root 4096 9月 18 10:43 20220918104301_access.log
drwxr-x---. 2 root root 4096 9月 18 10:44 20220918104401_access.log
drwxr-x---. 2 root root 4096 9月 18 10:45 20220918104502_access.log
drwxr-x---. 2 root root 4096 9月 18 10:46 20220918104601_access.log
drwxr-x---. 2 root root 4096 9月 18 10:47 20220918104701_access.log
drwxr-x---. 2 root root 4096 9月 18 10:48 20220918104801_access.log
drwxr-x---. 2 root root 4096 9月 18 10:49 20220918104901_access.log
drwxr-x---. 2 root root 4096 9月 18 10:50 20220918105001_access.log
drwxr-x---. 2 root root 4096 9月 18 10:51 20220918105101_access.log
drwxr-x---. 2 root root 4096 9月 18 10:52 20220918105201_access.log
如果想要删除定时任务,可以进入crontab -e,删除刚才写的任务。
crontab -l #查看任务状态
crontab -e #进入编辑添加定时任务
删除之后,crontab -l 查看一下刚才写的定时任务是否被删除