我经历了single line inifinite while loop在 bash 中,并尝试在有条件的循环中添加一行。下面我提到了我的命令,它给出了意想不到的结果(它应该在 2 次迭代后停止,但它永远不会停止。而且它认为变量 I 是可执行的)。
命令:
i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i = $i + 1; done
输出:
hi
The program 'i' is currently not installed. To run 'i' please ....
hi
The program 'i' is currently not installed. To run 'i' please ....
hi
The program 'i' is currently not installed. To run 'i' please ....
...
...
注意:我在 Ubuntu 14.04 上运行它
最佳答案
bash
特别注意变量赋值中的空格。 shell 将 i = $i + 1
解释为命令 i
并将其余部分解释为 i
的参数,这就是为什么你会看到错误是说 i
没有安装。
在 bash
中只需使用算术运算符(参见 Arithmetic Expression ),
i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; ((i++)); done
你也可以在循环上下文中使用算术表达式
while((i++ < 2)); do echo hi; sleep 1; done
基于 POSIX
i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; i=$((i+1)); done
POSIX shell 支持在数学上下文中使用 $(( ))
,这意味着使用 C 整数算法的语法和语义的上下文。
关于linux - 带条件的 Bash 单行 while 循环的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908224/