shell 压缩和删除日志的作业,每月一次

shell job to compress & delete logs, once in a month

我正在尝试 运行 将 centOS 上的作业安排到 .gz 并从目录中删除整整一个月的日志。日志名为 somelogfile_12Apr19_18_19_41.log、somelogfile_28Mar19_07_08_20.log

我可以运行下面的脚本来手动完成这个任务

tar -cvzf somezipfile_Mar19.tar.gz somelogfile_**Mar** --remove-files

计划的作业应在每个月的第 5 天 运行 压缩和删除前几个月的日志。自动化脚本会是什么样子?我被困在如何根据月份名称(一月、二月、三月等)仅包含前几个月的日志

要解决的第一个问题是您想要一个更通用的函数,它可以 运行 任何一个月并产生正确的结果。 date.

是获取所需信息(缩写月份和年份的最后两位数)的好工具
date -d "last month" +%b

2019 年 4 月 1 日 运行 时将产生 "Mar"。

date -d "last month" +%b%y

2019 年 4 月 1 日 运行 时将产生 "Mar19"。

现在我们知道如何获取我们想要的信息了,将 date 命令放在 tar 命令中将自动产生您要查找的结果。

tar -cvzf somezipfile_$(date -d "last month"%b%y).tar.gz somelogfile_**$(date -d "last month" +%b)** --remove-files

存在的最后一个问题是调度,可以使用 cron 解决。以下语句将 运行 /bin/foobar,在每个月的第 5 天添加到您的 crontab 文件中。 (crontab -e 编辑您的 crontab 文件)

0 0 5 * * /bin/foobar

将所有内容结合在一起,您将得到:

0 0 5 * * /bin/tar -cvzf somezipfile_$(date -d "last month"\%b\%y).tar.gz somelogfile_**$(date -d "last month" +\%b)** --remove-files

不要忘记在 crontab 中转义 %