Redirecting output of the bash keyword time
In a shell script I wanted to take the execution time of a command and redirect it to a file. First I tried the following:
time command > time.txt
It didn't work. Then I found out that the time command prints its output to stderr. I changed the command to:
time command 2> time.txt
It didn't work either. The time's output was still printed on the console.
It turned out that time is a reserved word in bash. It's not like most of the builtin commands in bash but it's a true part of the command line syntax like 'if' or 'while'.
Redirecting the output of the bash time can be achieved by executing the whole command (including the time part) in a subshell as follows:(time command) 2> time.txt
Launching a subshell is not necessary. Redirecting output of a code block works as well.
{ time ls; } 2> time.txt
This will probably be more efficient that executing the external /usr/bin/time command . Also the bash time command may have some features you need. Or you want to rely on bash time because you don't know if the system installed time utility will have the features you need or not.
In redirection and pipe behaviour this is actually the equivavelnt of executing the external time command /usr/bin/time .
Suppressing the output from the command itself can be made by redirecting its standard output and standard error to /dev/null
{ time command > /dev/null 2>&1 ; } 2> time.txt