bash-在单个管道阶段中设置多个变量 [英] bash -- setting multiple variables in a single pipeline stage

查看:34
本文介绍了bash-在单个管道阶段中设置多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望做类似的事情:

echo 1 2 | read foo bar

要将两个新变量foo和bar分别设置为值1和2.(实际上,"echo 1 2"将是对外部数据源的awk/cut调用.)

To set two new variables, foo and bar, to the values 1 and 2 respectively. (In reality, "echo 1 2" will be an awk / cut invocation for an external data source.)

我发现在此行之后不存在foo和bar,这使我想知道这是否是范围界定问题?我只使用read in while循环,在这种情况下,循环主体可以访问变量.

I am finding that foo and bar do not exist after this line which makes me wonder if it is a scoping issue? I have only used read in while loops and in those cases the loop body was able to access the variables.

推荐答案

管道在子外壳中执行.这样,将创建变量 foo bar ,将1和2存储在其中,然后退出子外壳,然后返回到父外壳,其中这些变量不存在存在.

Pipes execute in a sub-shell. As such, the variables foo and bar are created, 1 and 2 are stored in them, then the subshell exits and you return to the parent shell in which these variables do not exist.

一种将 read 读入变量的方法是使用"

One way to read into variables as you appear to want is with a "here string"

read foo bar <<<"1 2"

将执行您期望管道版本执行的操作.

Which will do what you expected the pipe version to do.

这是不可移植的,但是某些外壳程序将不支持它.您可以使用"此处为文档"形式,即受到广泛支持.

This is non-portable, however, and some shells will not support it. You can use the "here document" form instead, which is broadly supported.

$ read foo bar <<EOF
> 1 2
> EOF

请注意,此处的 EOF 可以是任何唯一字符串.此处的文档将存储所有行,直到包含 EOF 或您选择的任何标记的行,再没有其他行.在这种情况下,其行为也与前面的示例相同(但更难于复制和粘贴,而且键入时间更长).

Note that EOF here can be any unique string. A here document will store all lines until one that contains EOF, or whatever marker you chose, and nothing else. In this case the behavior is also identical with the previous example (but harder to copy and paste and longer to type).

这是怎么回事?

"here文档"和"here字符串"都是表示传递到标准输入的文本的方法,而无需交互输入.在功能上等效于只说 read foo bar ,按Enter,然后手动编写 1 2 然后再次按Enter.

Both the "here document" and the "here string" are ways to represent text passed to standard input without having to enter it interactively. It is functionally equivalent to just saying read foo bar, hitting enter, then manually writing 1 2 and hitting enter again.

这篇关于bash-在单个管道阶段中设置多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆