问题描述
猛砸允许使用:猫≤(回声$ FILECONTENT)
击还允许使用:而读我;做回声$ I;完成< / etc / passwd文件
要previous两人这才可以用来组合:回声$ FILECONTENT |而读我;做回声$ I;做
to combine previous two this can be used: echo $FILECONTENT | while read i; do echo $i; done
与最后一个问题是,它创建子shell和一段时间后结束循环变量 I
不能访问了。
The problem with last one is that it creates sub-shell and after the while loop ends variable i
cannot be accessed any more.
我的问题是:
如何实现这样的事情:而读我;做回声$ I;做≤(回声$ FILECONTENT)
或者换句话说:我怎样才能确保 I
while循环生存
How to achieve something like this: while read i; do echo $i; done <(echo "$FILECONTENT")
or in other words: How can I be sure that i
survives while loop?
请注意,我知道while语句封装成 {}
但这并不解决问题(假设你想使用while循环功能,然后返回 I
变量)
Please note that I am aware of enclosing while statement into {}
but this does not solves the problem (imagine that you want use the while loop in function and return i
variable)
推荐答案
正确的记法的是:
while read i; do echo $i; done < <(echo "$FILECONTENT")
的 I
在循环分配的最后一个值是那么当循环终止使用。
另一种方法是:
The last value of i
assigned in the loop is then available when the loop terminates.An alternative is:
echo $FILECONTENT |
{
while read i; do echo $i; done
...do other things using $i here...
}
的括号是一个I / O分组操作,不要自己创造一个子shell。在这种情况下,他们是一个管道的一部分,因此作为运行子shell,但它是因为的|
,而不是 {.. }
。您可以在这个问题提到这一点。据我所知,你可以从这些内部函数内部回报率。
The braces are an I/O grouping operation and do not themselves create a subshell. In this context, they are part of a pipeline and are therefore run as a subshell, but it is because of the |
, not the { ... }
. You mention this in the question. AFAIK, you can do a return from within these inside a function.
猛砸还提供内置和它的许多选项之一是:
Bash also provides the shopt
builtin and one of its many options is:
lastpipe
如果设置和作业控制处于不活动状态,外壳运行在当前shell环境背景不执行管道的最后一个命令。
If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.
因此,使用像这样的在脚本的使modfied 之
可循环后:
Thus, using something like this in a script makes the modfied sum
available after the loop:
FILECONTENT="12 Name
13 Number
14 Information"
shopt -s lastpipe # Comment this out to see the alternative behaviour
sum=0
echo "$FILECONTENT" |
while read number name; do ((sum+=$number)); done
echo $sum
在命令行中执行此操作通常运行的犯规作业控制处于不活动状态(即在命令行中,作业控制处于活动状态)。本测试不使用脚本失败。
Doing this at the command line usually runs foul of 'job control is not active' (that is, at the command line, job control is active). Testing this without using a script failed.
此外,如由在他,有时你可以在这里使用:
Also, as noted by Gareth Rees in his answer, you can sometimes use a here string:
while read i; do echo $i; done <<< "$FILECONTENT"
这不需要禁用了javascript
;你可以用它来保存一个过程。
This doesn't require shopt
; you may be able to save a process using it.
这篇关于巴什 - 如何管输入到while循环结束后环和preserve变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!