具有条件的Bash单行while循环的语法

时间:2017-12-20 14:28:10

标签: linux bash shell while-loop

我在bash中经历了single line inifinite while loop,并试图在带有条件的循环中添加一行。下面我提到了我的命令,它给出了意想不到的结果(假设在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上运行它

2 个答案:

答案 0 :(得分:8)

bash特别关于变量赋值中的空格。 shell将i = $i + 1解释为命令i,将其余部分解释为i的参数,这就是为什么您看到错误表明未安装i。< / p>

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-LY

i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; i=$((i+1)); done

POSIX shell支持在数学上下文中使用$(( )),这意味着使用C的整数运算的语法和语义的上下文。

答案 1 :(得分:2)

i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i=$(($i + 1)); done

相关问题