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

时间:2012-02-23 00:00:27

标签: 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

我的问题:有没有办法将输出的某些重定向到终端而不使用使用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

}

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

2 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:8)

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

echo "hello world" > /dev/tty

举个小例子:

$ 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
$ 
相关问题