我是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。
有人可以为此提供一些线索吗?
答案 0 :(得分:0)
您可以使用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
答案 1 :(得分: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
另一个好的编码实践是避免使用``,back-ticks进行命令替换并使用${..}
语法,并且还可以使用cat
无用,
time_status=$(tail -c 14 file | cut -d')' -f1)
date_now=$(date +%Y%m%d-%H%M)