get values from 'time' command via bash sc

2019-01-12 05:53发布

This question already has an answer here:

I want to run some executables with the time command

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?

4条回答
看我几分像从前
2楼-- · 2019-01-12 06:30

See BashFAQ/032.

All output (stdout, stderr and time) captured in a variable:

var=$( { time myexec -args; } 2>&1 )

Output to stdout and stderr go to their normal places:

exec 3>&1 4>&2
var=$( { time myexec -args 1>&3 2>&4; } 2>&1 )  # Captures time only.
exec 3>&- 4>&-
查看更多
Bombasti
3楼-- · 2019-01-12 06:32

Something like this?

TIME="$(sh -c "time myexec -args &> /dev/null" 2>&1)"
查看更多
Ridiculous、
4楼-- · 2019-01-12 06:37

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.

The explicit path is /usr/bin/time on Ubuntu, but you can find it out with $ 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.

STUFF_HERE=`/usr/bin/time -f %E sleep 1 2>&1`

查看更多
何必那么认真
5楼-- · 2019-01-12 06:47

Actually, I found this as well - How to store a substring of the output of "time" function in bash script

Probably closer to what I was looking for

查看更多
登录 后发表回答