为什么此循环不中断(由于if语句而结束)或使用新增加的$c变量的值?尝试使用 c = expr $ c + 1 (带和不带"双引号)。

export c=1; ssh auser@someserver "until [[ 1 -eq 2 ]]; do echo \"Value of 'c' == $c\"; c=`expr $c + 1`; echo \"$c - Incremented value: `expr $c + 1`\"; if [[ $c -gt 5 ]]; then break; fi; sleep 2 ; done;"

要么
$ export c=1; ssh root@$CHEF_SERVER \
> "until [[ 1 -eq 2 ]]; do \
>   echo \"Value of 'c' == $c\"; c=`expr $c + 1`; \
>   echo \"$c - Incremented value: `expr $c + 1`\"; \
>   if [[ $c -gt 5 ]]; then break; fi; \
>   sleep 2; \
>   echo; \
> done;"

输出是无限的:我必须^ c它。
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Value of 'c' == 1
1 - Incremented value: 2
Killed by signal 2.

最佳答案

您需要了解,在双引号下ssh内的条件变量或赋值中使用 shell 变量之前,必须正确转义它们。否则,即使在远程计算机上执行命令之前,变量也会扩展。因此,在您的情况下,无论您增加c还是不扩展变量,条件都始终在远程计算机中保持如下所示。

if [[ 1 -gt 5 ]]; then
    break
fi

另外expr已经过时了,使用传统的C风格循环增量(使用((..))作为)并转义变量内部的所有调用以延迟变量扩展
ssh root@$CHEF_SERVER "
until [[ 1 -eq 2 ]]; do
    ((c = c+1))
    echo "Incremented value: \$c"
    if [[ \$c -gt 5 ]]; then
        break
    fi
    sleep 2
done"

关于linux - 直到循环不终止或保持递增的变量的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55014700/

10-12 04:10
查看更多