我正在尝试为bash编写一个小函数,如下所示:
alias timesec='/usr/bin/time --format="%C took %e seconds"'
prun() {
echo \$ $@
timesec $*
}
但是当我使用它时,我得到:
mpen@mpen:/topsecret$ prun echo foo && echo bar
$ echo foo
foo
echo foo took 0.00 seconds
bar
我希望第一行说$ echo foo && echo bar
,而timesec
也应适用于整个命令(echo foo && echo bar
),而不仅仅是前半部分。
我该怎么做?
答案 0 :(得分:1)
您可以使用TIMEFORMAT
变量来自定义bash内置time
的输出:
cmd="/bin/echo foo && /bin/echo bar"
# See man bash for the TIMEFORMAT variable
PREV_TIMEFORMAT="${TIMEFORMAT}"
TIMEFORMAT="The command ${cmd} took %lR"
# You could use time eval "${cmd}". I don't recommend that
time /bin/echo foo && /bin/echo bar
输出:
foo
bar
The command /bin/echo foo && /bin/echo bar took 0m0.00s
注意:当您使用bash的内置echo
时,上述“解决方案”不起作用。