如何(...)和{...}与在bash管道子shell创建互动? [英] How do ( ... ) and { ... } interact with subshell creation with pipes in bash?

查看:226
本文介绍了如何(...)和{...}与在bash管道子shell创建互动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解使用圆括号和大括号外壳调用子之间的差异。我认为,大括号不启动的子进程,但似乎他们推出一个子进程。

I'm trying to understand a difference between shell subprocess invocation using round brackets and curly brackets. I thought that curly brackets do not launch a subprocess, but it seems that they do launch a subprocess.

#!/bin/sh

a=1
b=1

( a=2; ) | ( a=3; )
{ b=2; } | { b=3; }

echo "a=$a"
echo "b=$b"

本脚本打印

a=1
b=1

如此看来,所有的调用都内的子进程运行。有没有在这方面,它们之间有什么区别?我明白,如果我会使用&放大器;&安培; || ,那么 {。 } 不会启动子,但我想了解的管道是如何工作的。

So it seems that all invocations are run inside subprocesses. Is there any difference between them in that context? I understand that if I would use && and ||, then {..} will not launch a subprocess, but I'm trying to understand how pipes work.

推荐答案

要证明它正在生成子shell管道本身,而且大括号不会改变这两种方式:

To demonstrate that it's the pipeline itself that's generating the subshell, and that curly braces won't change this either way:

#!/bin/bash

echo "Base: $BASHPID"
( echo "In (): $BASHPID" )   # This will differ from the base
{ echo "In {}: $BASHPID"; }  # This will match the base

# In bash, these will both differ from the base
echo "Pipeline, default config:"
{ echo " X: $BASHPID" >&2; } | { echo " Y: $BASHPID" >&2; }

# This is exactly the same without the {}s
echo "Pipeline, no {}s, default config:"
echo " X: $BASHPID" >&2 | echo " Y: $BASHPID" >&2

# Only the former will differ from the base if running a new enough bash
shopt -s lastpipe
echo "Pipeline, lastpipe enabled:"
{ echo " X: $BASHPID" >&2; } | { echo " Y: $BASHPID" >&2; }

在bash 4.3运行这个地方,我得到:

Running this locally with bash 4.3, I get:

Base: 82811
In (): 82812
In {}: 82811
Pipeline, default config:
 X: 82813
 Y: 82814
Pipeline, no {}s, default config:
 X: 82815
 Y: 82816
Pipeline, lastpipe enabled:
 Y: 82811
 X: 82817

请注意,由于所有的管道组件同时运行,没有定义排序其中 X中将发出输出第一;然而,随着 lastpipe 启用,最后的管道组件在一个外壳,是已经投入运行(并不需要调用叉()编了从主进程),这略微修改的谁写第一到标准输出的可能性。

Note that since all pipeline components run simultaneously, there's no defined ordering of which of X or Y will emit output first; however, with lastpipe enabled, the last pipeline component is invoked in a shell that's already up and running (doesn't need to be fork()ed off from the main process), which slightly modifies the likelihood of who writes to stdout first.

这篇关于如何(...)和{...}与在bash管道子shell创建互动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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