0

check this out

$ time echo 1
1

real    0m0.000s
user    0m0.000s
sys     0m0.000s
$ TESTVAR=TEST time echo 1
1
0.00user 0.00system 0:00.00elapsed 0%CPU (0avgtext+0avgdata 1932maxresident)k
0inputs+0outputs (0major+74minor)pagefaults 0swaps

I have worked around this by exporting the variable beforehand, but am curious to know why this is.

(ubuntu and bash)

Alex028502
  • 469
  • 7
  • 12

2 Answers2

3

When you used the ENV=val form, you ran a different command than the bash time built-in (you ran the GNU time program from /usr/bin/time).

If you want to use the shell built-in, use it like this:

$ time TESTVAR=TEST echo 1
1

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

$ time TESTVAR=TEST printenv TESTVAR
TEST

real    0m0.003s
user    0m0.004s
sys     0m0.000s
  • yeah - or in other words `/usr/bin/time echo 1` gives me the funny looking output as well – Alex028502 Jun 27 '19 at 08:51
  • `/usr/bin/time` has an `-f` option to control its format, but it doesn't seem able to format the second values as the `bash` built-in. The `-p` option will let it print them on separate lines, though. –  Jun 27 '19 at 09:00
1

This is closely related to the reason behind a recent question: Why does a brace command group need spaces after the opening brace in POSIX Shell Grammar?

time, like {, is a reserved word, and a reserved word can't appear after variable assignment.

bash-5.0$ foo=bar { echo $foo; }
bash: syntax error near unexpected token `}'
bash-5.0$ foo=bar if true; then echo; fi
bash: syntax error near unexpected token `then'
bash-5.0$ foo=bar if true
bash: if: command not found

Since time isn't recognized as a reserved word in TESTVAR=TEST time echo 1, it undergoes normal command execution, looking for aliases, functions and (in this case, ending up with) external command execution.

muru
  • 69,900
  • 13
  • 192
  • 292