如何仅当过了一天才运行 bash 脚本?

如何仅当过了一天才运行 bash 脚本?

我希望经常运行我的脚本(不是通过 cron 而是手动),但有些缓慢的部分应该apt-get update && apt-get -y upgrade每天最多运行一次。

我想保存上次执行时间/tmp/last_update.txt并检查它是否超过now - 86400但无法理解如何使用 bash 使其变得更好。

不接受 Cron - 运行这些操作而不检查应用程序是很危险的。此外,执行这些任务时应用程序不稳定,不需要每天运行 - 仅在手动运行脚本(部署应用程序)时运行,但每天不超过一次。

例子:

some-fast-command-1

if [ not-run-command-2-for-24h ]; then
    some-slow-command-that-makes-app-unstable

    date > /tmp/last-run-command-2 # save last run time somehow
fi

some-fast-command-3

如何以not-run-command-2-for-24hbash 方式编写条件?

在 PHP 中我做了类似的事情

<?php
$filename = '/tmp/last-run-command-2';
$needRun = (!is_file($filename) && time() > file_get_contents($filename) + 86400);
if ($needRun) {
    run();
    file_put_contents($filename, time());
}

答案1

我找到了答案:
https://askubuntu.com/a/163570/26790

您可以获取当前时间戳:
now=$(date --date=$(date --iso-8601) +%s 2>/dev/null)

从文件加载时间戳:
stamp=$(date --date=$(date -r $stamp_file --iso-8601) +%s 2>/dev/null)

比较:
delta=$(($now-$stamp))
interval=$(($interval*60*60*24))
if [ $delta -ge $interval ]; then

相关内容