0

I want to use a time command in a script and put it into a variable (I will have to use it for many commands) so than I can modify just the single variable.

Simplified, this is how I tried it:

PROFILING="/usr/bin/time -f 'time: %e - cpu: %P'" ; $PROFILING ls /usr

I would expect that to be translated into:

# /usr/bin/time -f 'time: %e - cpu: %P' ls /usr
bin  games  include  lib  local  sbin  share  src
time: 0.00 - cpu: 0%

However I get this:

/usr/bin/time: cannot run %e: No such file or directory
Command exited with non-zero status 127
'time:

Any suggestion?

Thanks

Fabio
  • 65

1 Answers1

2

Word splitting doesn't understand quotes in the expanded variables. Use an array instead:

profiling=(/usr/bin/time -f 'time: %e - cpu: %P')
"${profiling[@]}" ls /usr

Or alias:

shopt -s expand_aliases # needed in scripts
alias profiling="/usr/bin/time -f 'time: %e - cpu: %P'"
profiling ls /usr

Or function:

profiling() { /usr/bin/time -f 'time: %e - cpu: %P' "$@"; }
profiling ls /usr
choroba
  • 47,233