如何在 bash 中撤销 exec > /dev/null?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17840322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:00:43  来源:igfitidea点击:

How to undo exec > /dev/null in bash?

bash

提问by user2267134

I used

我用了

exec > /dev/null

to suppress output.

来抑制输出。

Is there a command to undo this? (Without restarting the script.)

是否有命令可以撤消此操作?(无需重新启动脚本。)

回答by Charles Duffy

To do it right, you need to copy the original FD 1 somewhere else before repointing it to /dev/null. In this case, I store a backup on FD 5:

要做到这一点,您需要先将原始 FD 1 复制到其他地方,然后再将其重新指向 /dev/null。在这种情况下,我将备份存储在 FD 5 上:

exec 5>&1 >/dev/null
...
exec 1>&5

Another option is to redirect stdout within a block rather than using exec:

另一种选择是在块内重定向标准输出而不是使用exec

{
    ...
} >/dev/null

回答by Vaughn Cato

If you just want to get output again at the command prompt, you can do this:

如果您只想在命令提示符下再次获得输出,您可以这样做:

exec >/dev/tty

If you are creating a script, and you want to have the output of a certain group of commands redirected, put those commands in braces:

如果您正在创建脚本,并且希望重定向某组命令的输出,请将这些命令放在大括号中:

{
   command
   command
} >/dev/null

回答by Berkant

Save the original output targets beforehand.

预先保存原始输出目标。

# $$ = the PID of the running script instance
STDOUT=`readlink -f /proc/$$/fd/1`
STDERR=`readlink -f /proc/$$/fd/2`

And restore them again using exec.

并使用exec.

exec 1>$STDOUT 2>$STDERR

If you use /dev/ttyfor restoration as in the answers above, contrary to this, you won't be able to do redirections in call-level, e.g. bash script.sh &>/dev/nullwon't work.

如果您/dev/tty像上面的答案一样用于恢复,与此相反,您将无法在呼叫级别进行重定向,例如bash script.sh &>/dev/null不起作用。

回答by Роман Горбач

To restore stdout I use

要恢复我使用的标准输出

unset &1

回答by chepner

Not really, as that would require changing the state of a running process. Even assuming you could, whatever you wrote before resetting standard output is truly, completely gone, as it was sent to the bit bucket.

不是真的,因为这需要更改正在运行的进程的状态。即使假设你可以,在重置标准输出之前你写的任何东西都真的,完全消失了,因为它被发送到位桶。