$ # captures output of command and time
$ time=$( TIMEFORMAT="%R"; { time ls; } 2>&1 ) # note the curly braces
$ # captures the time only, passes stdout through
$ exec 3>&1 4>&2
$ time=$(TIMEFORMAT="%R"; { time ls 1>&3 2>&4; } 2>&1)
bar baz
$ exec 3>&- 4>&-
The time will look like "0.000" using TIMEFORMAT="%R" which will be the "real" time.
Time writes its output to STDERR rather than STDOUT. Making matters worse, by default 'time' is a shell builtin command, so if you attempt 'time ls 2>&1' the '2>&1' only applies to 'ls'.
@Dennis Williamson's answer is great, but it doesn't help you store the command's output in one variable, and the output of time in another variable. This is actually not possible using file descriptors.
If you want to record how long a program takes to run, you could do this by just subtracting the start time from the end time. Here is a simple example that shows how many milliseconds a program took to run:
See BashFAQ/032.
The time will look like "0.000" using
TIMEFORMAT="%R"
which will be the "real" time.Time writes its output to STDERR rather than STDOUT. Making matters worse, by default 'time' is a shell builtin command, so if you attempt 'time ls 2>&1' the '2>&1' only applies to 'ls'.
The solution would probably be something like:
There are more fancy ways to do it, but that is the clear/simple way.
@Dennis Williamson's answer is great, but it doesn't help you store the command's output in one variable, and the output of
time
in another variable. This is actually not possible using file descriptors.If you want to record how long a program takes to run, you could do this by just subtracting the start time from the end time. Here is a simple example that shows how many milliseconds a program took to run:
This is not quite as accurate as the
time
command, but it should work perfectly fine for most bash scripts.Unfortunately Mac's
date
command doesn't support the%N
format, but you can installcoreutils
(brew install coreutils
) and usegdate
:The cleanest approach is to combine a temp file and use GNU's time.
This will not bypass normal command output and you don't have to care about the file either since it will be deleted on it own.