在 Linux shell/bash 脚本中比较时间戳的最佳方法?
Best way to compare Timestamps in Linux shell/bash script?
我必须每隔 ~10 分钟从我的 Red Hate Enterprise Linux 机器上的目录 /usr/local/healthcheck.txt
中读取一个纪元时间戳(以 秒 为单位)(轮询)。我需要对时间进行比较,以检查 healthcheck.txt
文件中的时间戳是否比当前 time/timestamp 或 早 50 分钟,如果 healthcheck.txt
不存在,抛出错误。 healthcheck.txt
文件中的时间戳通常如下所示(如上所述,在 秒 内):
1591783065
我使用 date -d @1591783065
将时间戳转换为人类可读并得到如下内容:
Tue Jun 9 16:22:57 UTC 2020
将当前时间戳与文件中的此时间戳进行比较并检查其是否早于 50 分钟的最佳方法是什么?
在Java中,我们有一个Date
包,可以只用compareTo
来比较times/dates,有没有简单的方法可以用shell/bash 脚本?
你为什么不坚持使用纪元时间?您可以通过
date +%s
,所以你只需要比较
if (( (healthcheck_time + 50*60) < $(date +%s) ))
then
# .... healthcheck older than 50 minutes
fi
我必须每隔 ~10 分钟从我的 Red Hate Enterprise Linux 机器上的目录 /usr/local/healthcheck.txt
中读取一个纪元时间戳(以 秒 为单位)(轮询)。我需要对时间进行比较,以检查 healthcheck.txt
文件中的时间戳是否比当前 time/timestamp 或 早 50 分钟,如果 healthcheck.txt
不存在,抛出错误。 healthcheck.txt
文件中的时间戳通常如下所示(如上所述,在 秒 内):
1591783065
我使用 date -d @1591783065
将时间戳转换为人类可读并得到如下内容:
Tue Jun 9 16:22:57 UTC 2020
将当前时间戳与文件中的此时间戳进行比较并检查其是否早于 50 分钟的最佳方法是什么?
在Java中,我们有一个Date
包,可以只用compareTo
来比较times/dates,有没有简单的方法可以用shell/bash 脚本?
你为什么不坚持使用纪元时间?您可以通过
date +%s
,所以你只需要比较
if (( (healthcheck_time + 50*60) < $(date +%s) ))
then
# .... healthcheck older than 50 minutes
fi