我有两个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
,因为在我的实际程序中,有一个将错误重定向到文件的选项,但我想发送到终端的消息是信息性的,而不是错误,应该总是显示在终端上。
在另一个FD上打开/dev/tty
。
exec 0< /dev/null
exec 1> /dev/null
exec 2> /dev/null
exec 3> /dev/tty
echo 'Hello, World!' >&3
每次想写入终端时,都可以直接写入/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
$