如何输出到屏幕覆盖重定向

Kev*_*gan 10 bash io-redirection shell-script

是否可以在 shell 脚本中在重定向 STDOUT 和 STDERR 时写入屏幕?

我有一个 shell 脚本,我想捕获 STDOUT 和 STDERR。该脚本可能会运行一个小时或更长时间,所以我想偶尔向屏幕写入一些状态消息,这些消息将显示而不是重定向(未捕获)。

举个简单的例子,我有一个 shell 脚本,比如说“./myscript.sh”:

#!/bin/sh -u

echo "Message A: This writes to STDOUT or wherever '1>' redirects to."
echo "Message B: This writes to STDOUT or wherever '1>' redirects to.">&1
echo "Message C: This writes to STDERR or wherever '2>' redirects to.">/dev/stderr
echo "Message D: This writes to STDERR or wherever '2>' redirects to.">&2
echo "Message E: Write this to 'screen' regardless of (overriding) redirection." #>???  
Run Code Online (Sandbox Code Playgroud)


然后,例如,当我像这样运行脚本时,我希望看到这个输出:

[~]# ./myscript.sh > fileout 2> filerr
Message E: Write this to 'screen' regardless of (overriding) redirection.
[~]# ./myscript.sh > /dev/null 2>&1
Message E: Write this to 'screen' regardless of (overriding) redirection.
[~]#    
Run Code Online (Sandbox Code Playgroud)


如果这不能“直接”完成,是否可以暂时停止重定向,然后在屏幕上打印一些内容,然后恢复重定向?

关于电脑的一些信息:

[~]# uname -srvmpio
Linux 3.2.45 #4 SMP Wed May 15 19:43:53 CDT 2013 x86_64 x86_64 x86_64 GNU/Linux

[~]# ls -l /bin/sh /dev/stdout /dev/stderr
lrwxrwxrwx 1 root root  4 Jul 18 23:18 /bin/sh -> bash
lrwxrwxrwx 1 root root 15 Jun 29  2013 /dev/stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Jun 29  2013 /dev/stdout -> /proc/self/fd/1
Run Code Online (Sandbox Code Playgroud)

cha*_*aos 6

试试这样的脚本:

#!/bin/bash
echo "to fd1" >&1
echo "to fd2" >&2
echo "to screen" >$(tty)
Run Code Online (Sandbox Code Playgroud)

当你调用它时,它看起来像这样:

user@host:~# ./script
to fd1
to fd2
to screen
user@host:~# ./script 1>/dev/null
to fd2
to screen
user@host:~# ./script 2>/dev/null
to fd1
to screen
user@host:~# ./script > /dev/null 2>&1
to screen
Run Code Online (Sandbox Code Playgroud)