通过 bash 脚本从“时间”命令获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4617489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get values from 'time' command via bash script
提问by Derek
I want to run some executables with the time command
我想用 time 命令运行一些可执行文件
time myexec -args
How can I store only the time output to a variable in bash? Thats the only part I care about for this script, not the output of the executable. Is there a way to get that value, or will I have to parse the text of the entire command?
如何仅将时间输出存储到 bash 中的变量?这是我关心这个脚本的唯一部分,而不是可执行文件的输出。有没有办法获得该值,还是我必须解析整个命令的文本?
采纳答案by Derek
Actually, I found this as well - How to store a substring of the output of "time" function in bash script
实际上,我也发现了这一点 - How to store a substring of the output of "time" function in bash script
Probably closer to what I was looking for
可能更接近我想要的
回答by Paused until further notice.
See BashFAQ/032.
参见BashFAQ/032。
All output (stdout, stderr and time
) captured in a variable:
time
在变量中捕获的所有输出(stdout、stderr 和):
var=$( { time myexec -args; } 2>&1 )
Output to stdout and stderr go to their normal places:
输出到 stdout 和 stderr 到它们的正常位置:
exec 3>&1 4>&2
var=$( { time myexec -args 1>&3 2>&4; } 2>&1 ) # Captures time only.
exec 3>&- 4>&-
回答by chris
Something like this?
像这样的东西?
TIME="$(sh -c "time myexec -args &> /dev/null" 2>&1)"
回答by karatedog
BASH has its built-in variant of time
. If you do a man time
you will find that a lot of those option listed there won't work with time
command. The man page warns BASH users that they may use explicit path to time
.
BASH 有其内置的time
. 如果您执行 aman time
您会发现其中列出的许多选项不适用于time
命令。手册页警告 BASH 用户,他们可能会使用time
.
The explicit path is /usr/bin/time
on Ubuntu, but you can find it out with $ which time
.
显式路径/usr/bin/time
在 Ubuntu 上,但您可以使用$ which time
.
With the proper path, you can use the -f
or --format
option and a lot of formatting parameters that will nicely format your result which you can store to a variable as well.
使用正确的路径,您可以使用-f
or--format
选项和许多格式化参数,这些参数可以很好地格式化您的结果,您也可以将其存储到变量中。
STUFF_HERE=`/usr/bin/time -f %E sleep 1 2>&1`
STUFF_HERE=`/usr/bin/time -f %E sleep 1 2>&1`