linux - 带条件的 Bash 单行 while 循环的语法

标签 linux bash shell while-loop

我经历了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/

相关文章:

linux - 确定定义 UNIX 别名的位置

linux - Bash:为什么我不能为变量分配绝对路径?

linux - 从压缩文件中快速 grep 多个值

python - 如何在应用程序中嵌入图形交互式 IronPython shell?

linux - 试图将特定文件复制到特定文件夹,但有一个问题

linux - 无法识别的 Vim 键盘映射

linux - 使用 bash 脚本检查网络中不同计算机的信息

bash - 男人 grep | grep "color"没有给出结果

Bash:循环多个输入源(嵌套 "while read"循环?)

linux - 如何通过 add_custom_command 指定 LD_LIBRARY_PATH?