如何沉默Bash脚本中的输出?
我有一个程序,输出到标准输出,并希望沉默输出在Bash脚本pipe道到一个文件。
例如,运行该程序将输出:
% myprogram % WELCOME TO MY PROGRAM % Done. 我想要下面的脚本不输出任何东西到terminal:
 #!/bin/bash myprogram > sample.s 
	
如果它输出到stderr,你会想要保持沉默。 你可以通过redirect文件描述符2来做到这一点:
 # Send stdout to out.log, stderr to err.log myprogram > out.log 2> err.log # Send both stdout and stderr to out.log myprogram &> out.log # New bash syntax myprogram > out.log 2>&1 # Older sh syntax # Log output, hide errors. myprogram > out.log 2> /dev/null 
 2>&1 
与此你将redirectstderr(这是描述符2)到文件描述符1,这是标准输出
 myprogram > sample.s 
现在,当执行此操作时,您将stdoutredirect到sample.s文件
 myprogram > sample.s 2>&1 
组合这两个命令将导致将stderr和stdoutredirect到sample.s
 myprogram 2>&1 /dev/null 
如果你想完全沉默你的应用程序
所有输出:
 scriptname &>/dev/null 
便携性:
 scriptname >/dev/null 2>&1 
便携性:
 scriptname >/dev/null 2>/dev/null 
对于更新的bash(不可移植):
 scriptname &>- 
如果你想STDOUT和STDERR都[一切],那么最简单的方法是:
 #!/bin/bash myprogram >& sample.s 
 然后像./script那样运行,你将不会得到输出到你的terminal。  🙂 
  “>&”表示STDERR和STDOUT。  &也与pipe道相同的方式: ./script |& sed将所有东西都发送到sed 
 如果你仍然在努力寻找答案,特别是如果你为输出产生一个文件,你更喜欢清晰的select: echo "hi" | grep "use this hack to hide the oputut :) " echo "hi" | grep "use this hack to hide the oputut :) " 
试试:
 myprogram &>/dev/null 
得不到输出