I am trying to time something using:
/usr/bin/time myCommand
However, since /usr/bin/time
writes to stderr, if myCommand also writes to stderr, I will get more than just time's output on the stream. What I want to do is, redirect all of myCommand's output to /dev/null
, but still write time's output to stderr. Using an example myCommand that writes to stderr of ls /nofile
, we see that (obviously) there is no output at all with the following:
$ /usr/bin/time ls /nofile 2> /dev/null
$
Without any redirection, we see both the output from ls
(to stderr) and the output from time (also to stderr):
$ /usr/bin/time ls /nofile
ls: cannot access /nofile: No such file or directory
0.00user 0.00system 0:00.00elapsed 0%CPU (0avgtext+0avgdata 3776maxresident)k
0inputs+0outputs (0major+278minor)pagefaults 0swaps
What I want is something that simply produces:
$ /usr/bin/time ls /nofile > RedirectThatImAskingFor
0.00user 0.00system 0:00.00elapsed 0%CPU (0avgtext+0avgdata 3776maxresident)k
0inputs+0outputs (0major+278minor)pagefaults 0swaps
Any ideas?
Best Answer
In ksh, bash and zsh,
time
is a keyword, not a builtin. Redirections on the same line apply only to the command being timed, not to the output oftime
itself.To redirect the output from
time
itself in these shells, you need to use an additional level of grouping.If you use the GNU version of the standalone
time
utility, it has a-o
option to write the output oftime
elsewhere than stderr. You can maketime
write to the terminal:If you want to keep the output from
time
on its standard error, you need an extra level of file descriptor shuffling.With any
time
utility, you can invoke an intermediate shell to perform the desired redirections. Invoking an intermediate shell to perform extra actions such ascd
, redirections, etc. is pretty common — it's the kind of little things that shells are designed to do.