在 bash 中内联插入文件描述符 3 的输出
Inserting the output of file descriptor 3 inline in bash
我在 ruby 中编写了一个名为 citeselect
的程序,它使用 curses 动态 select 来自 bibtex bibliogrpahy 的引用。我想将该程序放入管道中,以便使用该程序的输出轻松引用任何内容。不幸的是,正如我从
Ncurses and linux pipeline (c),
Curses 使用 stdout
进行显示。
因此,当它作为输出提供时,我已将输出引用密钥路由到文件描述符 3 中。我已经验证它有效:
citeselect 3>output
有什么方法可以在 bash 中捕获发送到 fd3
的输出吗?像
echo "The citation key is $(citeselect 3>)"
谢谢。
问得好,更好的方法是使用 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,但在某些情况下,您应该避免使用该指南作为参考。
以 Victory 的回答为起点,在尝试输出重定向后,我意识到我对 n>&m 所做的事情有错误的想法。本指南对我帮助很大:
http://mywiki.wooledge.org/BashFAQ/002
为此,我必须将 stdout 重定向到 stderr,然后将 fd3 重定向到 stdout,如下所示:
CITATION=$(citeselect 3>&1 1>&2)
这样 curses 仍然可以通过 stderr 流使用 tty,而我仍然可以通过管道传输引文输出。在我早期的许多尝试中,由于对他们在做什么的根本误解,我颠倒了重定向参数。
我在 ruby 中编写了一个名为 citeselect
的程序,它使用 curses 动态 select 来自 bibtex bibliogrpahy 的引用。我想将该程序放入管道中,以便使用该程序的输出轻松引用任何内容。不幸的是,正如我从
Ncurses and linux pipeline (c),
Curses 使用 stdout
进行显示。
因此,当它作为输出提供时,我已将输出引用密钥路由到文件描述符 3 中。我已经验证它有效:
citeselect 3>output
有什么方法可以在 bash 中捕获发送到 fd3
的输出吗?像
echo "The citation key is $(citeselect 3>)"
谢谢。
问得好,更好的方法是使用 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,但在某些情况下,您应该避免使用该指南作为参考。
以 Victory 的回答为起点,在尝试输出重定向后,我意识到我对 n>&m 所做的事情有错误的想法。本指南对我帮助很大:
http://mywiki.wooledge.org/BashFAQ/002
为此,我必须将 stdout 重定向到 stderr,然后将 fd3 重定向到 stdout,如下所示:
CITATION=$(citeselect 3>&1 1>&2)
这样 curses 仍然可以通过 stderr 流使用 tty,而我仍然可以通过管道传输引文输出。在我早期的许多尝试中,由于对他们在做什么的根本误解,我颠倒了重定向参数。