Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 在不使用stderr将stdout重定向到文件后写入终端?_Bash_Shell_Redirect_Stdout - Fatal编程技术网

Bash 在不使用stderr将stdout重定向到文件后写入终端?

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

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

在“程序”的几个地方,我将执行类似的操作:
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
$