我是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
从现在开始一切都很好,脚本做了它必须做的事情,但是我需要得到好的答案,并在时间± 3 分钟时以 0 退出,不完全相同。
有人可以提供一些线索吗?
你可以通过这种方式操纵日期,
# 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)
您可以使用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