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)

0

2 Answers 2

2

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
2
  • yeah - or in other words /usr/bin/time echo 1 gives me the funny looking output as well
    – Alex028502
    Jun 27, 2019 at 8: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.
    – mosvy
    Jun 27, 2019 at 9: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.