Bash – Write Time Difference Command Output to File

bashio-redirectionshell-scripttime

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.

Best Answer

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.

Related Question