1

为什么这个循环没有中断(由于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.
4

2 回答 2

2

您需要了解 shell 变量需要正确转义ssh,然后才能在双引号内的条件或赋值中使用它们。不这样做会使变量在远程机器上执行命令之前扩展。因此,在您的情况下,无论您是否增加c或不扩展变量,并且远程机器中的条件始终如下所示。

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

expr已经过时了,使用传统的 C 风格循环增量使用((..))as 并转义内部变量的所有调用以推迟变量扩展

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"
于 2019-03-06T03:03:10.323 回答
0

变量在双引号字符串内展开。反引号也是如此。

您声明一个变量c并为其赋值1

然后调用ssh并传递一个双引号字符串。

ssh 调用的 shell 看到:

until [[ 1 -eq 2 ]]; do 
   echo "Value of 'c' == 1"; c=2; 
   echo "1 - Incremented value: 2"; 
   if [[ 1 -gt 5 ]]; then break; fi; 
   sleep 2; 
   echo; 
done;
于 2019-03-06T03:05:04.040 回答