get values from 'time' command via bash sc

2019-01-12 05:52发布

问题:

This question already has an answer here:

  • How to store a substring of the output of “time” function in bash script 3 answers

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?

回答1:

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>&-


回答2:

Something like this?

TIME="$(sh -c "time myexec -args &> /dev/null" 2>&1)"


回答3:

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



回答4:

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`