bash-管道创建一个子壳 [英] bash - pipe creates a subshell

查看:70
本文介绍了bash-管道创建一个子壳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,此读取是在管道之后执行的,这意味着回声的输出将被读取到 str 中-但是因为它在管道之后,所以 str 现在位于父shell无法读取的子shell中.我的问题是- str 的内容会怎样?管道是否创建了子外壳,然后将内容读入 str ,父进程是否杀死了子进程并删除了 str -还是 str 位于外壳外部的某个位置.就像我们如何看待子壳中的东西?我们可以从父外壳访问子外壳吗?

So this read is executed after the pipeline, which means that the output of the echo gets read into str - but because it is after a pipe, the contents of str are now in a subshell that cannot be read by the parent shell. My questions is - what happens in to the contents of str ? Does the pipe create a subshell, and then once the content are read into str , does the parent process kill the child process and str is erased - or does the contents of str live on somewhere outside the shell. Like how do we see what is in the subshells ? Can we access subshells from the parent shells?

echo hello | read str
echo $str

推荐答案

在您的示例中, $ str 存在于子外壳中,默认情况下,它在行结束后消失.子进程无法修改其父进程.

In your example, $str exists inside a subshell and by default, it disappears once the line has finished. A child process cannot modify its parent.

除了更改外壳选项 lastpipe 外,还可以更改代码以避免使用管道.在这种情况下,您可以使用:

Aside from changing the shell option lastpipe, you can also change the code to avoid using a pipe. In this case, you could use:

read str < <(your command) 
# or
str=$(your command)

这两个都创建了子shell,但是在父进程中将 $ str 分配给了.

Both of these create subshells too, but $str is assigned to in the parent process.

这篇关于bash-管道创建一个子壳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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