Bash 在不使用stderr将stdout重定向到文件后写入终端?
我有两个shell脚本,一个用作主“程序”,另一个用作“库” 在“程序”的几个地方,我将执行类似的操作:Bash 在不使用stderr将stdout重定向到文件后写入终端?,bash,shell,redirect,stdout,Bash,Shell,Redirect,Stdout,我有两个shell脚本,一个用作主“程序”,另一个用作“库” 在“程序”的几个地方,我将执行类似的操作:log“$thing”>>“$logfile”,其中log是在“库”中定义的函数 我的问题:是否有一种方法可以将函数的一些输出重定向回终端,而不使用stderr # library.sh log () { # This gets written to the log echo "`date --rfc-3339=seconds`: $1" # How to write thi
log“$thing”>>“$logfile”
,其中log
是在“库”中定义的函数
我的问题:是否有一种方法可以将函数的一些输出重定向回终端,而不使用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
exec 0/dev/null
exec 2>/dev/null
执行3>/dev/tty
回声“你好,世界!”>&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
$
有趣的。。。你能解释一下发生了什么事吗?还有前三行的意义是什么?这似乎只适用于最后两个。而且,我想我应该把第四行放在
program.sh
中,而不是每次调用log
时都执行它?前三行只是说明原来的描述符现在是无用的。对于更复杂的程序来说,这是一个简单的替身。前三个是为了表明脚本没有其他与外界交流的方式(例如,忙于做其他事情)。我会把exec
行放在library.sh中,但为了以防万一,我会给它一个更高的数字(比如8左右)。如果你只是运行manexec
,你会得到错误的页面manbash
,然后搜索短语,它将替换shell
。(在bash(1)
manpage中搜索exec
,这是一种快速发疯的方法。)@GGG:correct;任何兼容POSIX的shell都将提供内置的exec
shell。(好吧,它不必是内置的,但作为一个外部程序提供它将是非常困难的。我能想象的唯一合理的实现是shell内置。)我刚刚想起较新的bash
还提供了一个帮助
shell内置,您可能喜欢:帮助执行
。它不像手册页那样详细,但也许有一天正是您所需要的。:)谢谢你。我想把这两个标记都正确,但我必须把这一个给Ignacio,以获得exec
特殊酱汁:)这exec
特殊酱汁很干净。:)
$ 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
$