Running `exec` with a Bash built-in

bashcommand lineshell

I defined a shell function (let's call it clock), which I want to use as a wrapper to another command, similar to the time function, e.g. clock ls -R.

My shell function performs some tasks and then ends with exec "$@".

I'd like this function to work even with shell built-ins, e. g. clock time ls -R should output the result of the time built-in, and not the /usr/bin/time executable. But exec always ends up running the command instead.

How can I make my Bash function work as a wrapper that also accepts shell built-ins as arguments?

Edit: I just learned that time is not a Bash built-in, but a special reserved word related to pipelines. I'm still interested in a solution for built-ins even if it does not work with time, but a more general solution would be even better.

Best Answer

  • You defined a bash function. So you are already in a bash shell when invoking that function. So that function could then simply look like:

      echo "do something"

    That function can be invoked with bash builtins, special reserved words, commands, other defined functions:

    An alias:

    $ clock type ls
    do something
    ls is aliased to `ls --color=auto'

    A bash builtin:

    $ clock type type
    do something
    type is a shell builtin

    Another function:

    $ clock clock
    do something
    do something

    An executable:

    $ clock date
    do something
    Tue Apr 21 14:11:59 CEST 2015
  • Related Question