Bash Alias – How to Force a Bash Word to Reference an Alias, Function, File, etc.

bash

When trying to add a bit more detail to a related question, I realized I don't know how to specify which one of the available Bash word types to execute. According to help type there are five word types:

  • alias
  • keyword
  • function
  • builtin
  • file

It's possible for a word to have several types (true is just an example; a more commonly overridden word would be cd):

$ type -a true
true is a shell builtin
true is /bin/true

How do you force the execution of a specific synonym? So far, in order of precedence:

  • alias: This is a special case since it has precedence over all the other synonyms. Forcing this would only be useful when the command should fail if the alias is not defined.

    $ 
    
  • keyword:

    $ 
    
  • function:

    $ 
    
  • builtin:

    $ builtin true
    
  • file:

    $ command true
    $ $(which true)
    $ /bin/true
    

Partial solutions:

  • Quoting a word excludes aliases and keywords. That is,

    $ 'true'
    

    will run only the function, builtin or file.

Best Answer

What you're asking doesn't really make much sense.

keyword means it's a word that is part of the syntax of the shell. Those are recognised through tokenising. Quoting them is enough for the shell to stop recognising.

It is possible to alias a keyword in most shells though. So, aliases have precedence over keywords (in effect they are expanded early, and there is more tokenising after that where you can have more aliases, keywords)...

aliases (with the exception of zsh aliases defined with alias -g are only expanded in command position), so typically not in builtin the-alias.

functions have precedence over builtins, and builtins over external commands (and then $PATH decides which one to use).

You can force the builtin with:

builtin the-cmd and its args

(though it should be noted it is not a standard command).

You can disable aliases by quoting them (though the quoted version could also be aliased in some shells).

So, for instance (here zsh syntax), in:

'while'() echo function while
alias 'while=echo alias while'

Writing while true would actually output alias while true, and there would be no way to use the while keyword since quoting it would disable both the alias and keyword.

You would call the while function with for instance:

'whi'le whatever

If there was a while builtin (but of course their wouldn't in those shells that have while keyword), you'd write it:

builtin while whatever

And to call the while command, you'd write:

env while whatever

or in zsh (when not in sh emulation):

command while whatever 

(in other shells, command only prevents functions, not builtins)

Or

/full/path/to/while whatever

Of course, nothing's stopping you from doing even sillier things like:

alias 'while=while "w"hile; do'
"while"() { while "whi"le; done; }

Which, at least in zsh is valid (but stupid).