在Bash中,如何在已经重定向的情况下打印到stdout?

问题描述 投票:0回答:1

我正在编写一个Bash函数,比如说func() { … },交互式地询问用户几个问题,然后运行某个命令。

这里的奖项是所述命令的stdout,我希望用户可以这样调用我的函数:func >outfile,在文件中捕获命令的输出。

我的问题是,如何在不污染有用输出的情况下将这些交互式问题打印到stdout

换句话说:在函数内,如果stdout可能被调用者重定向,我如何写入'原始'stdout(终端),暂时忽略调用者的重定向?

我是否必须使用stderr来输出语义上不属于那里的输出?

bash file-descriptor io-redirection
1个回答
2
投票

Answering The Original Question

在定义函数的时间点创建原始标准输出的备份,并且可以在调用时使用它。

exec {myfunc_stdout_fd}>&1
myfunc() {
  echo "Content sent to stdout as defined at invocation time"
  echo "Content sent to original stdout" >&"$myfunc_stdout_fd";
}

...其后:

myfunc_out=$(myfunc)

...将qazxsw poi存储在qazxsw poi中,并立即将qazxsw poi写入函数定义发生时定义的stdout。

Content sent to stdout as defined at invocation time的在线翻译中看到这个


Advice Re: Best-Practice Usage

提示通常在UNIX上写入stderr,因此出于提示相关的目的,通常不需要保留原始stdout。提示stderr是myfunc_out所做的;什么是bash本身(就像其他shell一样);这是合适的,因为POSIX将stderr定义为“诊断输出”的适当流,这是一个包含程序当前正在做什么的状态的类别(它是否已准备好接收更多输入,f / e)。

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.