【问题标题】:compare time in bash script with ± x min将 bash 脚本中的时间与 ± x min 进行比较
【发布时间】:2017-03-18 08:33:11
【问题描述】:

我是 bash 新手,需要一些建议。

我有一个 .txt 文件,里面有一个时间戳,每 x 次重新加载一次,每个时间戳都是当前日期和时间。

"20221218-0841"

现在我已经构建了一个 bash 脚本来检查内容并给我一个答案,如果它是相同的。

#!/bin/bash
time_status=`cat /root/test.txt | tail -c 14 | cut -d')' -f1`

date_now=`date +%Y%m%d-%H%M`

if [ "$date_now" == "$time_status" ]
then
    echo "OK - $time_status "
    date +%Y%m%d-%H%M
    exit 0
fi

if [ "$date_now" != "$time_status" ]
then
    echo "WARNING - $time_status "
    date +%Y%m%d-%H%M
    exit 1
fi

从现在开始一切都很好,脚本完成了它必须做的事情,但是当时间不完全相同时,我需要得到答案并以 0 退出。

有人可以提供一些线索吗?

【问题讨论】:

  • 你能输出date --version吗?你有FreeBSD 日期还是GNU 日期/
  • 日期(GNU coreutils)8.4
  • 对不起,如果我写错了,但这里是全新的:(

标签: linux bash time compare


【解决方案1】:

你可以这样操作日期,

# Reading only the '%H%M' part from two variables using read and spitting
# with '-' de-limiter

IFS='-' read _ hourMinuteFromFile <<<"$time_status"
IFS='-' read _ currentHourMinute <<<"$date_now"

# Getting the diff only for the minutes field which form the last two
# parts of the variable above  

dateDiff=$(( ${hourMinuteFromFile: -2} - ${currentHourMinute: -2} ))

# Having the condition now for the difference from -3 to 3 as below,

if (( -3 <= ${dateDiff} <=3 )); then
    echo "OK - $time_status "
fi

试运行,

time_status="20170318-1438"
date_now="20170318-1436"
dateDiff=$(( ${hourMinuteFromFile: -2} - ${currentHourMinute: -2} ))

echo "$dateDiff"
2

另一个良好的编码习惯是避免使用 ``、反引号来替换命令并使用 ${..} 语法,同时也不要使用无用的 cat

time_status=$(tail -c 14 file | cut -d')' -f1)
date_now=$(date +%Y%m%d-%H%M)

【讨论】:

  • 感谢@Inian 你让我开心:)
  • @IllyrianB:很高兴能提供帮助。您还可以通过点击答案左侧附近的小 ^ 来为答案投票。
【解决方案2】:

您可以使用 date +%s 将日期转换为自 1970-01-01 00:00:00 UTC 以来的秒数,然后对结果执行通常的整数运算。

d1='2017-03-18 10:39:34'
d2='2017-03-18 10:42:25'

s1=$(date +%s -d "$d1")
s2=$(date +%s -d "$d2")
ds=$((s1 - s2))

if [ "$ds" -ge -180 -a "$ds" -le 180 ]
then
  echo same
else
  echo different
fi

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2019-01-17
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多