Search code examples
bashparameter-passingtiming

Passing multiple commands to script calling time


I have a bash script let's say foo.sh that in this minimal example looks like this:

#!/bin/bash
function __measure_time {
  time "$@"
}
__measure_time "$*"

What I want to do now is pass two commands to this script that are supposed to be run after another and I want to measure the time. So basically I am doing something like:

./foo.sh bash -c "echo 'ss' && sleep 1"

But that doesn't work the way I want it to. I don't get the 'ss' from the echo and the sleep is basically being ignored. Is there a way to make this work?


Solution

  • If you want the arguments to pass through correctly, you need to call __measure_time with "$@", not "$*":

    #!/bin/bash
    __measure_time() { #why the `function` syntax when you can be POSIX?
      time "$@"
    }
    __measure_time "$@"
    

    "$*" joins all arguments on the first character of $IFS into a string. "$@" is magic for "give me all the arguments, as if each was separately quoted."