bash 在不使用 stderr 的情况下将 stdout 重定向到文件后写入终端?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9405200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:38:01  来源:igfitidea点击:

Write to terminal after redirecting stdout to a file without using stderr?

bashshellredirectstdout

提问by Dagg Nabbit

I have two shell scripts, one that serves as the main "program" and another that serves as a "library."

我有两个 shell 脚本,一个用作主“程序”,另一个用作“库”。

In several places in the "program," I'll do something like: log "$thing" >> "$logfile", where logis a function defined in the "library."

在“程序”的几个地方,我会做这样的事情:log "$thing" >> "$logfile"log“库”中定义的函数在哪里。

# program.sh

logfile="log.txt"
stuff="hahah heheh hoho"

. library.sh 

for thing in $stuff; do
  log "$thing" >> "$logfile"
done

My question: Is there a way to redirect someof the output from the function back to the terminal withoutusing stderr?

我的问题:有没有办法在使用的情况下将函数的某些输出重定向回终端?stderr

# library.sh

log () {

  # This gets written to the log
  echo "`date --rfc-3339=seconds`: "

  # How to write this to the terminal *without* using stderr?
  echo "Info: Message written to log." >&2

}

I want to avoid the use of stderrbecause in my actual program, there's an option to redirect errors to a file, but the messages I want to send to the terminal are informational, not errors, and should always show up on the terminal.

我想避免使用,stderr因为在我的实际程序中,有一个选项可以将错误重定向到文件,但我想发送到终端的消息是信息性的,而不是错误,并且应该始终显示在终端上。

回答by Ignacio Vazquez-Abrams

Open /dev/ttyon another FD.

/dev/tty在另一个 FD 上打开。

exec 0< /dev/null
exec 1> /dev/null
exec 2> /dev/null
exec 3> /dev/tty
echo 'Hello, World!' >&3 

回答by sarnold

You can write directly to /dev/ttyeach time you want to write to the terminal:

/dev/tty每次要写入终端时都可以直接写入:

echo "hello world" > /dev/tty

For a small example:

举个小例子:

$ cat writer.sh 
#!/bin/sh

echo "standard output"
echo "standard error" >&2

echo "direct to terminal" > /dev/tty
$ ./writer.sh > /tmp/out 2> /tmp/err
direct to terminal
$ cat /tmp/out
standard output
$ cat /tmp/err
standard error
$