Mastering Command Resolution: Alias vs. Function Precedence
In this lesson, you will learn the precise order in which the Bash shell decides whether to execute an alias or a function when you type a command.
When you type a command into your terminal, Bash doesn't just guess what to do; it follows a strict internal search order. Before looking for an external binary or a built-in command, Bash checks if the name you typed exists as either an alias or a function.
The Rule of Hierarchy
The rule is simple: Aliases are always evaluated before functions.
If you happen to name an alias and a function with the same identifier, Bash will hit the alias first, execute it, and stop searching. It will never even "see" the function you defined.
Consider this scenario:
# Define a function
hello() { echo "I am a function!"; }
# Define an alias with the same name
alias hello="echo 'I am an alias!'"
# What happens when you run 'hello'?
hello
# Output: I am an alias!
Even though you defined the function perfectly, the alias takes precedence. Bash encounters the word hello, resolves it as an alias, expands the command, and executes it immediately. The function remains trapped in memory, completely unreachable by that name.
Why This Matters
This behavior is a common source of bugs in complex shell scripts or custom .bashrc files. You might define a sophisticated function to handle a task, only to find that an old alias (perhaps defined by your distribution or a legacy script) is overriding it.
To troubleshoot or avoid this, you can always check what a command resolves to by using the type built-in:
type hello
# Output: hello is aliased to `echo 'I am an alias!'`
If you ever need to bypass an alias to get to your function (or the original binary), you can use the unalias command or prefix your command with a backslash (e.g., \hello), which tells the shell to ignore the alias and look for the next item in the resolution order.
Key Takeaway: Bash resolves command names by checking aliases before functions, meaning an alias will always shadow a function with the same name.