2

I have a script tmp.sh

#!/bin/bash

echo hello
sleep 3
echo 3

I want to log the script running time (as well as script stdout) to a log file.

user$ time ./tmp.sh >& log.tmp

real    0m3.003s
user    0m0.000s
sys     0m0.003s

does not work.

user$ time ./tmp.sh 2>&1 log.tmp
hello
3

real    0m3.003s
user    0m0.002s
sys     0m0.001s

this also does not work.

What is the correct way to log the output of time command to log file?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

2

The time builtin of bash shows timing info on STDERR after the command after it (the actual one) returns. So unless you grouped them and pass the STDERR of the group to a file, only the actual command's STDERR will be redirected to the file and the file will be closed when command returns (prior to time shows its info).

You can use command grouping, redirecting both STDOUT and STDERR:

{ time ./tmp.sh ;} &>log.tmp  

Or run in a subshell:

( time ./tmp.sh ) &>log.tmp

Example:

$ { time sleep 1 ;} 2>time.log
$ cat time.log 

real    0m1.001s
user    0m0.000s
sys     0m0.000s


$ ( time sleep 1 ) 2>time.log
$ cat time.log 

real    0m1.001s
user    0m0.000s
sys     0m0.000s
heemayl
  • 56,300