[英]How do I properly set this variable?
I want to read a epoch time stamp from a file and then compare it with the current epoch time. 我想从文件中读取一个纪元时间戳,然后将其与当前纪元时间进行比较。
The comparison is not working and I get error: 比较不起作用,并且出现错误:
./script.sh: line 13: 1559122886- : syntax error: operand expected (error token is "- ") ./script.sh:第13行:1559122886-:语法错误:预期操作数(错误标记为“-”)
#!/bin/bash
RSTL=restart.log
if [ -f $RSTL ]; then
while IFS='|' read -r NRST LRST
do
echo "NRST is: $NRST"
echo "LRST is: $LRST"
done <$RSTL
CTIME=$(date +"%s")
echo "CTIME is: $CTIME"
fi
#LRST=$(date +"%s")
DIFF=$(( $CTIME-$LRST ))
echo "DIFF is: $DIFF"
if [[ $DIFF -gt 86400 ]]; then
echo "1|GREATER"
echo "1|$CTIME" > $RSTL
elif [[ $LRST -lt 86400 ]]; then
echo "LESS THAN"
echo "2|$CTIME" > $RSTL
else
echo "1|NEW"
echo "0|$CTIME" > $RSTL
fi
exit
When you mention an undeclared variable in $((..))
in variable expansion form (like $var
), it expands to empty string instead of zero, thus the error you get. 当您在$((..))
以变量扩展形式(如$var
)提到未声明的变量时,它会扩展为空字符串而不是零,因此会出现错误。 Don't use variable expansions in arithmetic expansions unless you have to. 除非必须,否则不要在算术扩展中使用变量扩展。 Change 13th line to following and you're good to go. 将第13行更改为跟随路线,一切就很好了。
DIFF=$((CTIME-LRST))
Another issue with your script is, you're populating NRST
and LRST
in a while loop, and this way those are unaccessible outside the loop. 脚本的另一个问题是,您将在while循环中填充NRST
和LRST
,这样,在循环外无法访问它们。 To fix it, replace the while loop with: 要解决此问题,请将while循环替换为:
IFS='|' read -r NRST LRST <"$RSTL"
echo "NRST is: $NRST"
echo "LRST is: $LRST"
And don't forget quoting all variable expansions to avoid word splitting. 并且不要忘记引用所有变量扩展名以避免单词拆分。
In line 12 remove "#" and in line 13 remove "$" from $CTIME and $LRST. 在第12行中,从$ CTIME和$ LRST中删除“#”,并在第13行中,删除“ $”。
#!/bin/bash
RSTL=restart.log
if [ -f $RSTL ]; then
while IFS='|' read -r NRST LRST
do
echo "NRST is: $NRST"
echo "LRST is: $LRST"
done <$RSTL
CTIME=$(date +"%s")
echo "CTIME is: $CTIME"
fi
LRST=$(date +"%s")
DIFF=$(( CTIME-LRST )) # Remove $ from $CTIME and $LRST
echo "DIFF is: $DIFF"
if [[ $DIFF -gt 86400 ]]; then
echo "1|GREATER"
echo "1|$CTIME" > $RSTL
elif [[ $LRST -lt 86400 ]]; then
echo "LESS THAN"
echo "2|$CTIME" > $RSTL
else
echo "1|NEW"
echo "0|$CTIME" > $RSTL
fi
exit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.