【问题标题】:bash file descriptor redirectionbash 文件描述符重定向
【发布时间】:2015-07-10 21:35:21
【问题描述】:

我有以下两个 bash 脚本:

一个.bash:

#!/bin/bash

echo "I don't control this line of output to stdout"

echo "I don't control this line of output to stderr" >&2

echo "I do control this line of output to fd 5" >&5

callone.bash:

#!/bin/bash

# here I try to merge stdout and stderr into stderr.
# then direct fd5 into stdout.

bash ./one.bash 1>&2 5>&1

当我这样运行它时: bash callone.bash 2>stderr.txt >stdout.txt

stderr.txt 文件如下所示:

I don't control this line of output to stdout
I don't control this line of output to stderr
I do control this line of output to fd 5

标准输出为空。

我希望将“控制”行仅输出到 stdout.txt。

进行更改的限制是:

  1. 我可以更改 callone.bash 中的任何内容。
  2. 我可以更改我控制的 one.bash 中的行。
  3. 我可以在 one.bash 中添加与文件描述符 5 相关的 exec。
  4. 我必须按照指示运行脚本。

[编辑] 这个用例是:我有一个脚本可以执行各种其他脚本的运行,这些脚本可以输出到 stderr 和 stdout。但我需要确保用户只能看到控制良好的消息。所以我将控制良好的消息发送到 fd5,其他所有内容(stdout 和 stderr)都发送到日志。

【问题讨论】:

    标签: bash


    【解决方案1】:

    重定向发生顺序

    运行 1>&2 后,您已将 fd 1 替换为 fd 2。

    因此,当您随后运行 5>&1 时,您会将 fd 5 重定向到 fd 1 指向的位置现在(而不是它开始时的位置)。

    你需要反转两个重定向:

    bash ./one.bash 5>&1 1>&2
    

    【讨论】:

    • 有趣的是,当管道参与进来时,它是一样的。
    • @o11c,首先设置管道,然后设置重定向。见stackoverflow.com/a/12027221/1524545
    • @o11c 有什么不一样的?
    • @EtanReisner 管道在右侧,但首先发生。
    • 啊,我明白了。这仍然是有序的,只是不是您可能天真的期望的顺序。当您了解各个部分必须如何协同工作时,这才有意义。其他任何东西都无法正确使用(无法正确使用 to/with 管道重定向)。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2011-07-03
    • 1970-01-01
    相关资源
    最近更新 更多