我试图做一个bash脚本中的以下内容,想知道是否有可能:
这是一个复杂的链条,我没有太多的运气一起工作。 如果我停止使用时间,我可以得到状态码。
这是我到目前为止:
# the setup TIMEFORMAT=%R MYSQL=mysql <options> # execute and time a query (does more than is listed here) function executeQuery { TIME=$( time ( $MYSQL "$1" 2>&1 | tee /tmp/somefile.txt > /dev/null ) 2>&1 ) # do something with $? }
我将命令的任何错误响应redirect到使用tee的文件,然后将生成的stdout发送到/ dev / null。 然后,我将时间命令的stderrredirect到stdout,这应该以$ TIME结束。
现在,如果我改变这样的行:
TIME=$( time ( $MYSQL "$1" 2>&1 | tee /tmp/somefile.txt > /dev/null; exit ${PIPESTATUS[0]} ) 2>&1 )
它正确地从mysql发回退出代码,但打破了时间命令。
这甚至有可能吗? 我错过了什么吗? 希望目标是明确的。
谢谢!
bash time是主要的PITA。 它的输出是不可redirect的,没有像你的多级子壳这样的讨厌的shell攻击。 http://mywiki.wooledge.org/BashFAQ/032build议正确答案是:
TIME = $( ( time $MYSQL "$1" 2>&1 | tee /tmp/somefile.txt > /dev/null; exit ${PIPESTATUS[0]} ) 2>&1 )
请注意,bash time将整个pipe道作为参数,因此在调用时间之后放置子shell是不正确的。
这是与testing
TIME = $( ( time ls /asdfasfdsfs 2>&1 | tee asdf 2>&1 >/dev/null ; exit ${PIPESTATUS[0]} ) 2>&1 ); echo $?; echo $TIME
哪给了我
2 real 0m0.003s user 0m0.004s sys 0m0.004s