简体   繁体   English

重定向所有命令的bash输出和错误

[英]redirect bash output and error for all commands

How to redirect all commands executed on the bash to /dev/null ? 如何将bash上执行的所有命令重定向到/ dev / null?

It's obvious that for a command we have to do: 很明显,对于我们必须做的命令:

command > /dev/null  2>&1

How about all commands that will be executed further on ? 所有将要执行的命令怎么样?

Simply start a new shell: 只需启动一个新shell:

bash >/dev/null 2>&1

Now you can type commands blind :) If you want to leave that mode type: exit 现在你可以输入命令blind :)如果你想离开那个模式类型: exit

But typing commands blind will normally not what you want. 但盲目输入命令通常不是你想要的。 So I would suggest to create a text file like script.sh , place your commands in it: 所以我建议创建一个像script.sh这样的文本文件,将命令放在其中:

command1 foo 
command2 bar

and than execute it using: 而不是使用以下方式执行:

bash script.sh >/dev/null 2>&1

The ouput of all commands in that script will be redirected to /dev/null now 该脚本中所有命令的输出现在将重定向到/ dev / null

Use exec without a command: 在没有命令的情况下使用exec

exec > /dev/null 2>&1

As hex2mgl pointed out, if you do this in an interactive shell, you won't even see your prompt anymore, as the shell prints that to standard error. 正如hex2mgl指出的那样,如果你在交互式shell中执行此操作,则甚至不会再看到提示符,因为shell会将其打印到标准错误。 I assume this is intended for a script, as it doesn't make a lot of sense to ignore all output from commands run interactively :) 我认为这是用于脚本,因为忽略来自交互式运行的命令的所有输出没有多大意义:)

for scripting or other practical purpose, grouping the command is a nice solution. 对于脚本或其他实际目的,对命令进行分组是一个很好的解决方案。 check http://www.gnu.org/software/bash/manual/html_node/Compound-Commands.html It says specifically Any redirections (see Redirections) associated with a compound command apply to all commands within that compound command unless explicitly overridden. 查看http://www.gnu.org/software/bash/manual/html_node/Compound-Commands.html具体说明Any redirections (see Redirections) associated with a compound command apply to all commands within that compound command unless explicitly overridden.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM