简体   繁体   English

解释这个 bash 重定向行为

[英]Explain this bash redirection behaviour

I was experimenting with redirections and pipes and did not understand some behaviour.我正在尝试重定向和管道,但不了解某些行为。 I have this snippet to generate one line on each of stderr and stdout:我有这个片段来在每个标准错误和标准输出上生成一行:

(echo stdout; echo stderr 1>&2)

It seems to work correctly, (try >/devnull and 2>/dev/null).似乎工作正常,(尝试 >/devnull 和 2>/dev/null)。

But the behaviour of these three commands confuses me:但是这三个命令的行为让我感到困惑:

(echo stdout; echo stderr 1>&2) > >(wc -l)
stderr
1
(echo stdout; echo stderr 1>&2) 2> >(wc -l)
stdout
1
(echo stdout; echo stderr 1>&2) > >(wc -l) 2> >(wc -l)
2
(empty)

Why does the last command combine the two streams?为什么最后一个命令将两个流结合起来? Or what else is happening to break my brain?或者还有什么事情让我的大脑崩溃了?

because the second wc -l derives stdout from current command (stdout already redirect to fist wc -l ), its output is also passed to first wc -l . 因为第二个wc -l从当前命令派生stdout (stdout已经重定向到第一个wc -l ),它的输出也传递给第一个wc -l

 IN   +-----------+   1>    +---------+         OUT
+-+--->echo stdout+----+---->  wc -l  +------------->
  |   +-----------+    ^    +---------+
  |                    |
  |                    |
  |                    +<------------------+
  |                                        |
  |                                        |
  |   +-----------+   2>    +---------+    |
  +--->echo stderr+--------->  wc -l  +----+
      +-----------+         +---------+

It is something like有点像

$ { echo stdout; echo stderr 3>&2 2>&1 1>&3 >&2 | wc -l; } | wc -l
2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM