我有一个程序输出到stdout,并希望在管道到文件时在Bash脚本中静音该输出.
例如,运行程序将输出:
% myprogram
% WELCOME TO MY PROGRAM
% Done.
Run Code Online (Sandbox Code Playgroud)
我希望以下脚本不向终端输出任何内容:
#!/bin/bash
myprogram > sample.s
Run Code Online (Sandbox Code Playgroud)
Joh*_*ica 172
如果它输出到stderr你也会想要沉默.你可以通过重定向文件描述符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
Run Code Online (Sandbox Code Playgroud)
Deb*_*ger 53
sample.s
有了这个,你将stderr(它是描述符2)重定向到文件描述符1,这是stdout
/dev/null
现在执行此操作时,您将stdout重定向到文件sample.s
sample.s
组合这两个命令将导致stderr和stdout重定向到sample.s
/dev/null
如果你想完全沉默你的应用程序
Edu*_*omo 34
所有输出:
scriptname &>/dev/null
Run Code Online (Sandbox Code Playgroud)
便携性:
scriptname >/dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)
便携性:
scriptname >/dev/null 2>/dev/null
Run Code Online (Sandbox Code Playgroud)
对于较新的bash(无便携式):
scriptname &>-
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 11
如果你想要STDOUT和STDERR [一切],那么最简单的方法是:
#!/bin/bash
myprogram >& sample.s
Run Code Online (Sandbox Code Playgroud)
然后运行就好了./script,你的终端没有输出.:)
">&"表示STDERR和STDOUT.对&管道也有同样的作用:./script |& sed
将所有内容发送到sed
如果您仍在努力寻找答案,特别是如果您为输出生成了一个文件,并且您更喜欢明确的替代方案:
echo "hi" | grep "use this hack to hide the oputut :) "