CRIS
CRIS

Reputation: 346

Why is the shell executing an alias instead of a function?

I've added some alias in .bashrc as shortcuts for git commands.
One example is ga for git add

But when I made some changes to the ga function like:

function ga() {
  echo "hello"
}

And use ga in the terminal, it is still using git add.
I tried to comment out ga by editing .bashrc, and then using source ~/.bashrc. However, it still executes the alias instead of the function.

What would be the cause?

Upvotes: 0

Views: 361

Answers (3)

fedorqui
fedorqui

Reputation: 290175

When you define an alias you have to take into account that they are looked up before functions:

$ alias hello="echo 'this is a hello alias'"
$ function hello() { echo "this is a hello function"; }
$ hello
this is a hello alias
#               ^^^^^  <--- it executes the alias, not the function!

So what's the way to call the function? Just use \ before its name. It will bypass the alias:

$ \hello
this is a hello function
#               ^^^^^^^^  <--- it executes the function now

You can also use unalias, so the alias is removed.

$ unalias hello
$ hello
this is a hello function
#               ^^^^^^^^

And what if the alias and the function have the name of a command? Then it comes handy using command:

$ alias date="echo 'this is an alias on date'"
$ function date() { echo "this is a function on date"; }
$ date
this is an alias on date
#          ^^^^^              <--- it executes the alias, not the function!
$ \date
this is a function on date
#         ^^^^^^^^            <--- it executes the function
$ command date
Thu Jan 21 10:56:20 CET 2021
# ^^^^^^^^^^^^^^^^^^^^^^^^^   <--- it executes the command

You can also use nice:

$ nice -n0 date
Thu Jan 21 10:56:20 CET 2021

As seen in Aliases vs functions vs scripts:

Aliases are looked up before functions: if you have both a function and an alias called foo, foo invokes the alias. (If the alias foo is being expanded, it's temporarily blocked, which makes things like alias ls='ls --color' work. Also, you can bypass an alias at any time by running \foo.) I wouldn't expect to see a measurable performance difference though.

Further reading:

Upvotes: 2

CRIS
CRIS

Reputation: 346

I've found an answer. I used unalias to remove the aliasing of ga

unalias ga

ga() {
  echo "ZAWARUDO"
}

Upvotes: 1

user1934428
user1934428

Reputation: 22301

You forgot to delete the old definitions. The easiest way would be to just open a new interactive bash shell. Instead of sourcing .bashrc, simply do a

bash

Of course this means that functions/aliases/non-exported variables, which you had manually definied in your current shell, also get lost.

Upvotes: 0

Related Questions