【问题标题】:Inserting the output of file descriptor 3 inline in bash在 bash 中内联插入文件描述符 3 的输出
【发布时间】:2017-12-05 12:34:24
【问题描述】:

我用ruby 编写了一个名为citeselect 的程序,它使用curses 从bibtex bibliogrpahy 中动态选择引用。我想将此程序放入管道中,以便使用该程序的输出轻松引用任何内容。不幸的是,正如我从 Ncurses and linux pipeline (c), Curses 使用stdout 显示。

因此,当输出引用键作为输出提供时,我已将其路由到文件描述符 3。我已经验证它可以工作:
citeselect 3>output

有什么方法可以在 bash 的单行中捕获发送到 fd3 的输出?类似
echo "The citation key is $(citeselect 3>)"

谢谢。

【问题讨论】:

  • 你已经接近了。 3>&1 将文件描述符 3 复制到文件描述符 1(标准输出)。如果 curses 实际上写入标准输出(而不是直接写入终端),您还需要通过一些扭曲来避免捕获它。

标签: bash file-descriptor output-redirect


【解决方案1】:

很好的问题,一个更好的方法是使用exec 命令将 stdout 文件描述符替换为另一个数字:

#!/usr/bin/env bash

exec 3>&1             # 1 is stdout, 3 is the fd to assign stdout to

exec > outputfile.txt # every command executed within this location 
                      # to where the fd was closed and replaced back 
                      # to it's formal value will be sent to outputfile.txt


citselect

exec 1>&3 3>&-        # the fd of stdout is replaced back to 1 and reset

将此文件放入您的${HOME}/bin/usr/bin/ 文件夹并执行它,而不是直接调用citeselect

有关这方面的更多信息,请查看Advanced Bash Guide,但在某些情况下,您应该避免使用该指南作为参考。

【讨论】:

    【解决方案2】:

    以 Victory 的回答为起点,在尝试了输出重定向之后,我意识到我对 n>&m 所做的事情有错误的想法。本指南对我很有帮助:
    http://mywiki.wooledge.org/BashFAQ/002

    为此,我必须将 stdout 重定向到 stderr,然后将 fd3 重定向到 stdout,如下所示:
    CITATION=$(citeselect 3>&1 1>&2)

    这样,curses 仍然能够通过 stderr 流使用 tty,而我仍然可以管道引用输出。在我早期的许多尝试中,由于对重定向参数的操作存在根本性的误解,我将重定向参数颠倒过来。

    【讨论】:

      猜你喜欢
      • 2015-02-05
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多