带条件的 Bash 单行 while 循环的语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47908224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Syntax for a Bash single-line while loop with condition
提问by rashok
I gone through single line inifinite while loopin bash, and trying to add a single line while loop with condition. Below I have mentioned my command, which gives unexpected result (It is suppose to stop after 2 iterations, but it never stops. And also it considers variable I as executable).
我在 bash 中经历了单行无限 while 循环,并尝试在有条件的 while 循环中添加单行。下面我提到了我的命令,它给出了意想不到的结果(假设在 2 次迭代后停止,但它永远不会停止。并且它还认为变量 I 是可执行的)。
Command:
命令:
i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i = $i + 1; done
Output:
输出:
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 ....
...
...
Note: I am running it on Ubuntu 14.04
注意:我在 Ubuntu 14.04 上运行它
回答by Inian
bash
is particular about spaces in variable assignments. The shell has interpreted i = $i + 1
as a command i
and the rest of them as arguments to i
, that is why you see the errors is saying i
is not installed.
bash
特别关注变量赋值中的空格。shell 已将其解释i = $i + 1
为一个命令i
,而其余的i
则被解释为 的参数,这就是为什么您看到错误提示i
未安装的原因。
In bash
just use the arithmetic operator (See Arithmetic Expression),
在bash
仅仅使用算术运算符(见算术表达式)
i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; ((i++)); done
You could use the arithmetic expression in the loop context also
您也可以在循环上下文中使用算术表达式
while((i++ < 2)); do echo hi; sleep 1; done
POSIX-ly
POSIX-ly
i=0; while [ "$i" -lt 2 ]; do echo "hi"; sleep 1; i=$((i+1)); done
POSIX shell supports $(( ))
to be used in a math context, meaning a context where the syntax and semantics of C's integer arithmetic are used.
POSIX shell 支持$(( ))
在数学上下文中使用,这意味着使用 C 整数算术的语法和语义的上下文。
回答by Viktor Khilin
i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i=$(($i + 1)); done
i=0; while [ $i -lt 2 ]; do echo "hi"; sleep 1; i=$(($i + 1)); done