ZSH:从使用相同名称的 zsh 函数调用内置函数 [英] ZSH: Call in-built function from zsh function that uses the same name
问题描述
我使用 zsh 并希望稍微扩展内置的 cd
功能.我希望当我调用cd
时,它直接改变,然后列出目录的内容.
I use zsh and would like to slightly extend the in-built cd
function.
I'd like that when I call cd
, it changes directly and then lists the content of the directory.
function cd() {
cd $1
ls .
}
我原以为这段代码可以工作,但事实证明,对 cd
的调用引用了函数定义,从而导致了无限循环.
I'd have expected this code to work, but as it turns out, the call to cd
refers to the function definition, resulting in an infinite loop.
除了为我的函数选择不同的名称外,是否有解决此问题的方法?
Is there a work-around to solve this problem, apart from choosing a different name for my function?
更新
奇怪的是,这奏效了
function cd() {
`echo $1`
ls .
}
不知道为什么.
推荐答案
为了在同名函数内或其他任何地方使用内置命令,您可以使用 builtin
前置命令修饰符:
In order to use builtin commands from within functions of the same name, or anywhere else for that matter, you can use the builtin
precommand modifier:
function cd() {
builtin cd $1
ls .
}
builtin COMMAND
告诉 zsh 使用名称为 COMMAND
的内置命令,而不是同名的别名、函数或外部命令.如果这样的内置函数不存在,则会打印一条错误消息.
builtin COMMAND
tells zsh to use the builtin with the name COMMAND
instead of a alias, function or external command of the same name. If such a builtin does not exist an error message will be printed.
对于要使用外部命令而不是别名、内置命令或同名函数的情况,可以使用 command
前置命令修饰符.例如:
For cases where you want to use an external command instead of an alias, builtin or function of the same name, you can use the command
precommand modifier. For example:
command echo foobar
这将使用二进制 echo
(很可能是 /bin/echo
)而不是 zsh 的 内置 echo
.
This will use the binary echo
(most likely /bin/echo
) instead of zsh's builtin echo
.
与函数不同,builtin
和 command
通常不需要别名来防止递归.虽然可以在别名定义中使用别名
Unlike with functions builtin
and command
are usually not necessary with aliases to prevent recursions. While it is possible to use an alias in an alias definition
% alias xx="echo x:"
% alias yy="xx y:"
% yy foobar
y: x: foobar
每个别名只会扩展一次.第二次出现时,别名不会被扩展,而是会使用函数、内置或外部命令.
each alias name will only expanded once. On the second occurence the alias will not be expanded and a function, builtin or external command will be used.
% alias echo="echo echo:"
% echo foobar
echo: foobar
% alias xx="yy x:"
% alias yy="xx y:"
% xx foobar
zsh: command not found: xx
当然,如果你想阻止使用另一个别名,或者你想使用一个内置或具体的外部命令.例如:
Of course, you can still use builtin
or command
in aliases, if you want to prevent the use of another alias, or if you want to use a builtin or external command specifically. For example:
alias echo="command echo"
有了这个,二进制 echo
将被用来代替内置的.
With this the binary echo
will be used instead of the builtin.
这篇关于ZSH:从使用相同名称的 zsh 函数调用内置函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!