带条件的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:41:24  来源:igfitidea点击:

Syntax for a Bash single-line while loop with condition

linuxbashshellwhile-loop

提问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

bashis particular about spaces in variable assignments. The shell has interpreted i = $i + 1as a command iand the rest of them as arguments to i, that is why you see the errors is saying iis not installed.

bash特别关注变量赋值中的空格。shell 已将其解释i = $i + 1为一个命令i,而其余​​的i则被解释为 的参数,这就是为什么您看到错误提示i未安装的原因。

In bashjust 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