bash:从管道分配变量? [英] bash: Assign variable from pipe?
问题描述
在bash
中,使用管道输入分配变量的最有效方法是什么-仅使用从左到右的语法?假设管道的左侧是seq 3
,所以我们想要:
In bash
, what's the most efficient way to assign a variable using piped input -- using only left to right syntax? Suppose the left side of the pipe is seq 3
, so we'd want:
seq 3 | x=<put some code here>
注意:虽然可能在功能上是等效的,但不是答案:
NB: Not an answer, although probably functionally equivalent:
x=`seq 3`
...因为seq 3
不在管道的左侧一侧.
...because seq 3
is not on the left side of a pipe.
对于这个问题,请忽略超出变量内存的可能性,管道肯定可以做到这一点.
For this Q, please ignore the possibility of exceeding the variable's memory, which pipes could certainly do.
推荐答案
以 Charles Duffy的有用答案为重点在bash
中的使之起作用上:
默认情况下,在Bash v4.1- 不变中,(多段)管道中的任何变量创建/修改都发生在 subshell ,这样结果就不会显示在调用shell中.
By default, and on Bash v4.1- invariably, any variable creations / modifications in a (multi-segment) pipeline happen in a subshell, so that the result will not be visible to the calling shell.
在 Bash v4.2 + 中,您可以设置选项lastpipe
,以使 last 管道段在中运行当前外壳程序,以便在那里可见 对其进行的变量创建/修改.
In Bash v4.2+, you can set option lastpipe
to make the last pipeline segment run in the current shell, so that variable creations/modifications made there are visible to it.
要使其在 interactive shell 中工作,必须另外使用set +m
关闭作业控制.
For that to work in an interactive shell, you must additionally turn off job control with set +m
.
这是一个完整的示例(Bash v4.2 +):
Here's a complete example (Bash v4.2+):
$ unset x; shopt -s lastpipe; set +m; seq 3 | x=$(cat); echo "$x"
1
2
3
说,
That said,
x=$(seq 3)
(相当于您的x=`seq 3`
的现代版本)要简单得多-它符合POSIX,因此也可以在较早的Bash版本上使用,并且不需要摆弄全局选项.
(the modern equivalent of your x=`seq 3`
) is much simpler - it is POSIX-compliant and therefore works on older Bash versions too, and it requires no fiddling with global options.
这篇关于bash:从管道分配变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!