为什么 shell 执行别名而不是函数?

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

我在 .bashrc 中添加了一些别名作为 git 命令的快捷方式。
一个例子是 ga for git add

但是当我对 ga 函数进行一些更改时,例如:

function ga() {
  echo "hello"
}

并在终端中使用ga,仍然使用git add
我试图通过编辑 .bashrc,然后使用 source ~/.bashrc 来注释掉 ga。但是,它仍然执行别名而不是函数。

会是什么原因?

您忘记删除旧定义。最简单的方法是打开一个新的交互式 bash shell。无需采购 .bashrc,只需执行

bash

当然,这意味着 functions/aliases/non-exported 变量(您在当前 shell 中 手动 定义的)也会丢失。

我找到了 answer。 我使用 unalias 删除了 ga

的别名
unalias ga

ga() {
  echo "ZAWARUDO"
}

当您定义别名时,您必须考虑到它们在 函数之前被查找:

$ 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!

那么函数的调用方式是怎样的呢? 只需在名称前加上\。它将绕过别名:

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

你也可以使用unalias,这样别名就去掉了。

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

如果别名和函数具有命令的名称怎么办?然后使用 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

你也可以使用nice:

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

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.

延伸阅读: