Redirect Output from Time Command to a File

If you want to find out how long a program takes to execute, you can use the Linux time command. It outputs the real, user and system resources used by the command you specify. For example, to see how long the ls command takes to execute on the current directory, you run time ls and get something like the following:

real 0m0.005s
user 0m0.004s
sys 0m0.000s

However, by default, the time command outputs this information to the standard error device and, as a result, it’s not always obvious how to get this information into a file.

If you’re using the GNU time command, it’s pretty easy with the -o or --output option. For example, the following command writes the time information from executing ls into the file time.log:

time -o time.log ls

On some systems, such as a Linux server I was using recently, the only available time command may be the one built into the shell. This time command does not have an output option. As a result, if you want to redirect the output of both the time command and the program it’s executing, you might think you want to do the following:

time ls > output.log 2>&1

Then, you discover that it doesn’t work as expected. All you get in the log file is the output of the ls command while the time command still prints to the console, even though you redirected standard error to standard out.

Why does this happen? It’s because those redirects apply only to the ls command, not to the time command. Fortunately, there’s an easy solution. Group the time command and the program you want it to time using parentheses. Try changing the previous command to the following:

( time ls ) > output.log 2>&1

When you view the output.log file now, you’ll find that the output of both the ls and time commands went into the log file, as desired.

One thought on “Redirect Output from Time Command to a File”

  1. Hello thank’s you for you post , i’m not find solutions for (time ls) > out.txt 2>&1 now you resolved me , anew thank you so much.

    Pd: Sorry by my bad english :S