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

Dag*_*bit 8 bash shell redirect stdout

我有两个shell脚本,一个用作主"程序",另一个用作"库".

在"程序"的几个地方,我会做类似的事情log "$thing" >> "$logfile",其中log是"库"中定义的函数.

# program.sh

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

. library.sh 

for thing in $stuff; do
  log "$thing" >> "$logfile"
done
Run Code Online (Sandbox Code Playgroud)

我的问题:有没有办法将函数的一些输出重定向回终端而不使用stderr

# library.sh

log () {

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

Ign*_*ams 12

打开/dev/tty另一个FD.

exec 0< /dev/null
exec 1> /dev/null
exec 2> /dev/null
exec 3> /dev/tty
echo 'Hello, World!' >&3 
Run Code Online (Sandbox Code Playgroud)

  • 如果你只是运行`man exec`,你会得到错误的页面.`man bash`,然后搜索"它取代shell"这个短语.(在'bash(1)`联机帮助页中搜索`exec`是一种快速的方法.) (5认同)

sar*_*old 8

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

echo "hello world" > /dev/tty
Run Code Online (Sandbox Code Playgroud)

举个小例子:

$ 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
$ 
Run Code Online (Sandbox Code Playgroud)