【问题标题】:shell job to compress & delete logs, once in a month用于压缩和删除日志的 shell 作业,每月一次
【发布时间】:2019-09-04 12:50:15
【问题描述】:

我正在尝试在 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 天运行一次,以压缩和删除前几个月的日志。自动化脚本会是什么样子?我被困在如何根据月份名称(Jan、Feb、Mar 等)仅包含前几个月的日志

【问题讨论】:

  • 你有什么问题?
  • 您应该搜索“cron” - 这就是您要搜索的内容。
  • 考虑使用-j (bzip2) 或-J (xz) 代替-z (gzip):xz 的压缩效果优于 bzip2,bzip2 的压缩效果优于 gzip。

标签: bash shell unix cron cron-task


【解决方案1】:

要解决的第一个问题是您需要一个更通用的函数,该函数可以在任何月份运行并产生正确的结果。 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 解决。以下语句将在每个月的第 5 天运行/bin/foobar,并将其添加到您的 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 中转义 %

【讨论】:

  • 太棒了!!这很整洁@Ghosy
猜你喜欢
  • 2015-03-25
  • 2023-03-15
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多