Search code examples
bashshellmetaprogramming

Wrapping shell built-ins


I'd like to wrap the built-in Bash command export so that it logs the variable being exported.

In a language like JavaScript, if I want to wrap a built-in, I can save a reference to the original object. So, for instance, we could make the built-in alert capitalize its argument:

var originalAlert = alert;
alert = function(s) {
  originalAlert(s.toUpperCase());
}

But since Bash doesn't have references like this, I don't think it's possible to wrap export with the same technique.

Am I wrong? Is there some way to wrap a bash built-in like export?


Solution

  • You can call a builtin, even if it has been overridden by a function, with the builtin command:

    export() {
        echo "$@"
        builtin export "$@"
    }