Turbotoad
Turbotoad

Reputation: 1

Difference in behaviour between time and /usr/bin/time in ubuntu 16.04

I am teaching myself bash scripting and trying to create a script that completes the exercise...

Write a script that stores the time it takes a command (your choice of command) to run in three variables, real, user, and system, corresponding to the three default times that time prints.

I have been playing around with something like

output=$( /usr/bin/time -f "%E\n" ( eval "$@" 2>/dev/null 1>&2) 2>&1 )

The plan is to use the format flag to get an output string in some arbitrary format that I can then split into separate variables. For extra cred I am also trying to suppress the output of the original command using a subshell and output redirection.

This of course does not work. Trying to run a script containing just this line and the input "ls -l" and I get an error

command substitution: line 14: syntax error near unexpected token `('

After some playing around I have noticed that...

time (ls -l)

Works fine but

/usr/bin/time (ls -l)

Gives the error

bash: syntax error near unexpected token `ls'

Why the difference in behaviour between the built-in and the binary?

Upvotes: 0

Views: 521

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263197

The difference is that the time command, unlike /usr/bin/time, is built into the shell, so it can do things that an external command cannot.

The shell sees

/usr/bin/time (ls -l)

as a command /usr/bin/time with arguments. Unescaped parentheses are not allowed in command arguments. You'll get the same error if you type, for example:

/bin/echo (ls -l)

or even, using the builtin command:

echo (ls -l)

The builtin time, on the other hand, is designed to be more flexible. In fact the builtin time is a keyword, not a command; it's part of the syntax of the shell.

Quoting the bash documentation:

The use of time as a reserved word permits the timing of shell builtins, shell functions, and pipelines. An external time command cannot time these easily.

Upvotes: 2

Related Questions