为什么这个循环没有中断(由于 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.
最佳答案
您需要了解 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"
关于linux - Until 循环不终止或保持增量变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55014700/