Bash单行while循环的语法及条件。

3
我通过bash中的单行无限循环,并尝试添加一个带条件的单行while循环。下面是我的命令,它给出了意外的结果(它应该在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上运行它。

1
如果你正在使用 i 的特定值进行循环,那么你不需要使用 while 循环。你应该使用:for((i=0;i<2;i++)); do ... ; done - William Pursell
2个回答

9

bash 对变量赋值中的空格非常敏感。Shell 将 i = $i + 1 解释为命令 i 和后面的参数,因此你会看到错误提示说 i 没有安装。

bash 中只需使用算术运算符(参见算术表达式)即可解决问题。

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语言整数算术的语法和语义。


2

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接