Can I write the output of the time difference command to a file?
For example, I tried:
$ time foo.sh > bar.txt
But it only gives the output of foo.sh to bar.txt.
Can I write the output of the time difference command to a file?
For example, I tried:
$ time foo.sh > bar.txt
But it only gives the output of foo.sh to bar.txt.
In many shells including ksh
, zsh
and bash
, time
is a keyword and is used to time pipelines.
time foo | bar
Will time both the foo
and bar
commands (zsh
will show you the breakdown). It reports it on the shell's stderr.
time foo.sh > bar.txt
Will tell you the time needed to open bar.txt
and run foo.sh
.
If you want to redirect time
's output, you need to redirect stderr
in the context where time
is started like:
{ time foo.sh; } 2> bar.txt
This:
2> bar.txt time foo.sh
works as well but with ksh93
and bash
, because it's not in first position, time
is not recognised as a keyword, so the time
command is used instead (you'll probably notice the different output format, and it doesn't time pipelines).
Note that both would redirect both the output of time and the errors of foo.sh
to bar.txt
. If you only want the time output, you'd need:
{ time foo.sh 2>&3 3>&-; } 3>&2 2> bar.txt
Note that POSIX doesn't specify whether time
behaves as a keyword or builtin (whether it times pipelines or single commands). So to be portable (in case you want to use it in a sh
script which you want portable to different Unix-like systems), you should probably write it:
command time -p foo.sh 2> bar.txt
Note that you can't time functions or builtins or pipelines or redirect foo.sh
errors separately there unless you start a separate shell as in:
command time -p sh -c 'f() { blah; }; f | cat'
But that means the timing will also include the startup time of that extra sh
.
/usr/bin/time
outputs to stderr
, so you will need to redirect that.
/usr/bin/time foo.sh 2>bar.txt
If you use bash' time
builtin, you need to write it differently:
(time ls) 2>bar.txt
Alternatively, GNU time
supports an --output
argument:
/usr/bin/time --output bar.txt foo.sh
Not all versions of time support the -o and --output arguments.
You will want to run the command like this:
(time script.sh) 1> /dev/null 2> /tmp/logFile
This will put the output of script.sh into /dev/null and the results to /tmp/logFile.
If you want both STDERR and STDOUT to go to the log file you can run it like this:
(time script.sh) &> /tmp/logFile
To get the output of ls
and the output of time
in the file:
(time ls) &> log
To get just the output of time
in the file:
(time ls) 2> log
/usr/bin/time -V
. There is also the time command built into bash. – slm May 09 '13 at 20:26(time ls) 2>bar.txt
it works fine. – slm May 09 '13 at 20:39