隐藏shell命令的输出通常涉及redirectstderr和stdout。 有没有内置的设施或命令默认隐藏输出,但错误转储所有累计输出? 我想运行这个作为远程ssh命令的包装。 现在我有他们使用redirect,但我不知道是什么让他们失败,他们只是太冗长。
编辑:最后,我创build了以下模板根据@Belmin的答案,我调整了一点累积脚本中的所有以前的命令,使用当前的进程标识符,自动删除日志,并添加一个失败的红色错误当出现错误时的消息。 在这个模板中,最初的silent包装将会成功,然后第三个命令失败,因为该目录已经存在:
#!/bin/sh set -e SILENT_LOG=/tmp/silent_log_$$.txt trap "/bin/rm -f $SILENT_LOG" EXIT function report_and_exit { cat "${SILENT_LOG}"; echo "\033[91mError running command.\033[39m" exit 1; } function silent { $* 2>>"${SILENT_LOG}" >> "${SILENT_LOG}" || report_and_exit; } silent mkdir -v pepe silent mkdir -v pepe2 silent mkdir -v pepe silent mkdir -v pepe2
我会设置一个bash函数,像这样:
function surpress { /bin/rm --force /tmp/surpress.out 2> /dev/null; ${1+"$@"} > /tmp/surpress.out 2>&1 || cat /tmp/surpress.out; /bin/rm /tmp/surpress.out; }
然后,你可以运行命令:
surpress foo -a bar
为此目的写一个脚本应该很容易。
像这样的完全未经testing的脚本。
OUTPUT=`tempfile` program_we_want_to_capture &2>1 > $OUTPUT [ $? -ne 0 ]; then cat $OUTPUT exit 1 fi rm $OUTPUT
另一方面,对于我作为脚本的一部分运行的命令,我通常要比打印所有输出更好。 我经常把我所看到的东西限制在未知之中。 这是一个我从十多年前阅读的东西改编的剧本。
#!/bin/bash the_command 2>&1 | awk ' BEGIN \ { # Initialize our error-detection flag. ErrorDetected = 0 } # Following are regex that will simply skip all lines # which are good and we never want to see / Added UserList source/ || \ / Added User/ || \ / init domainlist / || \ / init iplist / || \ / init urllist / || \ / loading dbfile / || \ /^$/ {next} # Uninteresting message. Skip it. # Following are lines that we good and we always want to see / INFO: ready for requests / \ { print " " $0 # Expected message we want to see. next } # any remaining lines are unexpected, and probably error messages. These will be printed out and highlighted. { print "->" $0 # Unexpected message. Print it ErrorDetected=1 } END \ { if (ErrorDetected == 1) { print "Unexpected messages (\"->\") detected in execution." exit 2 } } ' exit $?
我不认为有这样一个干净的方式,我唯一能想到的是
实现这可能是一个有趣的项目,但可能超出问答。
用tehcommand &>/tmp/$$ || cat /tmp/$$类的东西来tehcommand &>/tmp/$$ || cat /tmp/$$ tehcommand &>/tmp/$$ || cat /tmp/$$
取决于你想/需要多less可用性/打字。 (例如使用它作为pipe道或通过parameter passing命令)
@zoredache短脚本基本上是一个原始包装,这将提供更多的健壮性,处理并发性等
试试这样:
out=`command args...` || echo $out