在Linux shellbash脚本中比较时间戳的最佳方法?

问题描述 投票:0回答:1

我必须读取一个纪元时间戳(在 秒钟)从目录 /usr/local/healthcheck.txt 在我的Red Hate Enterprise Linux机器上,每隔10分钟(轮询)就会发生一次。我需要对时间进行一个比较,以检查在 healthcheck.txt 文件与当前时间戳相差50分钟以上。 如果 healthcheck.txt 是不存在的,抛出一个错误。中的时间戳是不存在的。healthcheck.txt 文件一般是这样的(它在 秒钟,如上所述)。

1591783065

我使用的是 date -d @1591783065 将时间戳转换为可读时间戳,得到这样的结果。

Tue Jun 9 16:22:57 UTC 2020

什么是最好的方法来比较当前的时间戳和文件中的时间戳,并检查其是否超过50分钟?

在Java中,我们有一个 Date 包,并可以只使用 compareTo 来比较时间日期,有什么简单的方法可以用shellbash脚本来实现吗?

bash shell datetime timestamp comparison
1个回答
4
投票

你为什么不坚持使用epoch-time?你可以通过以下方法获得当前时间为自纪元以来的秒数。date +%s所以你只需要比较

if (( (healthcheck_time + 50*60) < $(date +%s) ))
then
  # .... healthcheck older than 50 minutes
fi
© www.soinside.com 2019 - 2024. All rights reserved.