管道的左侧是子壳? [英] Left side of pipe is the subshell?

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

问题描述

我在下面关于 sed 's@^@ @' <(f1) 的评论是不正确的虽然 $BASH_SUBSHELL 表明我们与启动处于同一级别,但主脚本中的变量丢失了.基于 Gordons 的回答,我测试了 f1 >>(sed 's@^@ @') 而这似乎可以正常工作.不过,对于第一种形式,BASH_SUBSHELL 不应该是 1 而不是 0 吗?

My comment below regarding sed 's@^@ @' <(f1) is incorrect While $BASH_SUBSHELL indicates that we are in the same level as the launch, the variables are lost in the main script. based on Gordons answer I tested f1 > >(sed 's@^@ @') instead and that seems to work correctly. Still, shouldn't BASH_SUBSHELL should be 1 and not 0 for the first form?

考虑这个小测试

#!/bin/bash
declare -i i=0
function f1()
{
  let i++
  echo "In f1, SUBSHELL: $BASH_SUBSHELL, i=$i" >&2
}

f1
f1 | sed 's@^@     @'

echo "at end, i=$i"

具有以下输出:

In f1, SUBSHELL: 0, i=1
In f1, SUBSHELL: 1, i=2
at end, i=1

(sed 的目的只是为了有一个管道,不要指望它做任何事情,因为 f1 输出到 stderr)

(the purpose of the sed is just to have a pipe to something, don't expect it to do anything because f1 outputs to stderr)

函数 f1 记录当前的 BASH_SUBSHELL 和 i 的当前值

The function f1 logs the current BASH_SUBSHELL and the current value of i

我知道为什么在脚本的末尾我们得到 i=1,这是因为第二次调用是在子外壳中,而 i 的值位于子外壳 1丢失了.

I know why at the end of the script we get i=1, its because the second invocation was in a subshell, and the value of i at subshell 1 was lost.

我不知道的是为什么在当前shell中没有执行管道的左侧

What I don't know is why the left side of the pipe was not executed in the current shell

虽然我认为我可以用 sed 's@^@ @' <(f1)我想知道为什么左边和主脚本不在一个级别

Though I figured that I could avoid this with sed 's@^@ @' <(f1) I would like to know why the left side is not at the same level as the main script

推荐答案

来自 bash 手册页:"管道中的每个命令都作为一个单独的进程(即在一个子 shell 中)执行."我想可以在当前 shell 中执行管道的一个组件(即第一个,或最后一个,或者可能是中间的一个),它不会像这样播放收藏夹:他们all 在子 shell 中执行.如果您像这样修改脚本:

From the bash man page: "Each command in a pipeline is executed as a separate process (i.e., in a subshell)." I suppose it would be possible to execute one component of a pipeline in the current shell (i.e. the first, or the last, or maybe one in the middle), it doesn't play favorites like this: they all execute in subshells. If you modify your script like this:

#!/bin/bash
declare -i i=0
function f1()
{
    let i++
    echo "In f1, SUBSHELL: $BASH_SUBSHELL, i=$i" >&2
}

f1
f1 | f1 | f1

echo "at end, i=$i"

它打印:

In f1, SUBSHELL: 0, i=1
In f1, SUBSHELL: 1, i=2
In f1, SUBSHELL: 1, i=2
In f1, SUBSHELL: 1, i=2
at end, i=1

因为管道中对 f1 的所有 3 次调用都在子 shell 中运行.

because all 3 invocations of f1 in the pipeline run in subshells.

这篇关于管道的左侧是子壳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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