Bash time command output is different with environment variable assignment
Solution 1:
Why is this happening?
In Bash time
is a reserved word (keyword) that can precede and measure not only a simple command; it can measure a pipeline. As such, it must be the first word. This syntax only informs Bash that you want to measure time; the rest of the pipeline is still processed by Bash as if time
wasn't there.
If time
is not the first word and still can be interpreted as a command, it's interpreted as a regular external command (not even a builtin), looked up in $PATH
and executed; e.g. it can be /usr/bin/time
. This tool processes its arguments and builds the actual command from them.
The two utilities produce output in different formats.
And is there a way to keep variable assignment while having the output in three lines?
Yes. You can use time
as the first word, so it gets interpreted as the keyword:
time VAR="" sleep 2
Note both implementations support -p
that changes the output format to that specified by POSIX (in fact the support for -p
itself is required by POSIX). This means the following two commands will produce output in the same format:
time -p VAR="" sleep 2
VAR="" time -p sleep 2
Under the hood, however, these are very different.