gpt4 book ai didi

linux - 如何在 if 条件中使用 expr

转载 作者:可可西里 更新时间:2023-11-01 11:49:20 28 4
gpt4 key购买 nike

我有以下 if 条件:

STATUSFILE = "foo.status"
NEWTIME=1389253927
if [ -f $STATUSFILE ] && [ expr $NEW_TIME - cat $STATUSFILE -gt 3600 ]; then
echo "foo"
fi;

我得到 [: 参数太多了

最佳答案

if 的参数是一个 unix 命令。 [ 等同于testif 的结果取决于该命令的返回状态。

因此,如果你想测试命令的返回状态,你应该删除[

当你想检查命令的输出(而不是它的状态)时,你必须保留 [ 并将命令放在 $()

您的陈述应重写为:

if [ -f $STATUSFILE ] && [ $(expr $NEWTIME - $(cat $STATUSFILE)) -gt 3600 ]; then

比这更好的是使用由 $(( and )) 提供的 bash 的算术功能:

if [ -f $STATUSFILE ] && [ $(($NEWTIME - $(cat $STATUSFILE) )) -gt 3600 ]; then

关于linux - 如何在 if 条件中使用 expr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21014524/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com