4

In many cases I need to create functions with the same name as other programs, and I've no idea if it is a good way to use bash scripting.

Example:

    function echo () {
        echo -n "$@" ;
    }  

After testing it looks like it checks functions names inside script before bin paths. I want to make sure about that and any other info I should know.

7
echo() {
  command echo -n "$@"
}

Using command here means asking for the echo command (which happens to be builtin here) instead of the function one which otherwise would take precedence.

And since here, echo also happens to be a builtin (is not looked-up in $PATH BTW as builtins have precedence over filesystem commands), you could also do:

echo() {
  builtin echo -n "$@"
}

That latter approach is preferable in zsh, where command echo would run /bin/echo instead (except in sh emulation).

There are some subtle variations between shells, but the order of precedence is generally:

  1. special builtins
  2. functions
  3. builtins
  4. commands in $PATH (and the order depends on the order in $PATH and in the hash table as managed by the hash builtin)

Bearing in mind that aliases and keywords in the shell syntax (for, if...), when not quoted are considered before those.

The order of 1 and 2 is reversed in some shells like bash or zsh. bash doesn't allow functions to be defined with the same name as a special builtin when invoked as sh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.