Shell – expand aliases before calling /usr/bin/time

aliasshelltime-utility

When I use the shell builtin time, I can pass any command I would pass to the shell without time. But when I use the external /usr/bin/time, I cannot pass a shell alias, because /usr/bin/time is naturally not aware of those:

$ /usr/bin/time ll
/usr/bin/time: cannot run ll: No such file or directory

How can I convince the shell to expand the alias for ll before passing it on to /usr/bin/time? Parsing the output of alias ll is tricky, in particular since the definition of the alias contains other aliases.


My reason for using /usr/bin/time is to measure peak memory usage.

Best Answer

You can define an alias for /usr/bin/time as:

alias 'ubtime=/usr/bin/time '

Or

alias 'ubtime=command time '

if you don't want to hard code the path to the time executable.

The trick is in the trailing space in the alias definition that tells the shell that aliases must be substituted after that alias so that

ubtime ll

Will actually be expanded to

/usr/bin/time ls -l

(assuming ll is an alias to ls -l).

In any case, /usr/bin/time being a standalone executable, it cannot time pipelines or compound commands or functions or shell builtins, so it cannot time the expansion of arbitrary aliases.

If the reason for using /usr/bin/time is because you prefer its default output format over the one for the time keywork, note that in many shells, the format can be modified. For instance, in zsh:

$ TIMEFMT=$'\e[31;1m%J\e[m: U:%U S:%S (%*E total) [avgtext:%X avgdata:%D maxmem:%M]'
$ time ls -l | head -n1
total 288072444
ls -l: U:0.00s S:0.01s (0.017 total) [avgtext:0 avgdata:0 maxmem:3]
head -n1: U:0.00s S:0.00s (0.015 total) [avgtext:0 avgdata:0 maxmem:3]

(the \e[31;m for coloured (bold red) output).

Related Question