如何显示 zsh 函数定义(如 bash“type myfunc”)?

问题描述 投票:0回答:4

如何在 zsh 中显示函数的定义?

type foo
没有给出定义。

在重击中:

bash$ function foo() { echo hello; }

bash$ foo
hello

bash$ type foo
foo is a function
foo () 
{ 
    echo hello
}

在 zsh 中:

zsh$ function foo() { echo hello; }

zsh$ foo
hello

zsh$ type foo
foo is a shell function
bash function zsh definition
4个回答
130
投票

zsh 习惯用法是

whence
-f
标志打印函数定义:

zsh$ whence -f foo
foo () {
    echo hello
}
zsh$

在 zsh 中,

type
被定义为等同于
whence -v
,因此您可以继续使用
type
,但您需要使用
-f
参数:

zsh$ type -f foo
foo () {
    echo hello
}
zsh$

最后,在 zsh 中,

which
被定义为等同于
whence -c
- 以 csh-like 格式打印结果,因此
which foo
将产生相同的结果。

man zshbuiltins
对于这一切。


31
投票

我一直只使用

which
来实现此目的。


24
投票
declare -f foo  # works in zsh and bash

typeset -f foo  # works in zsh, bash, and ksh

如果您不介意或更喜欢在输出中包含给定名称存在的all命令形式:谢谢,Raine Revere

type -af  # zsh only (works differently in bash and ksh)

在这种情况下,

type -f
/
whence -f
/
which
不是最佳选择,因为它们的目的是报告具有 最高优先级 的命令形式,而恰好由该名称定义 - 而不是专门报告操作数作为函数

也就是说,实际上这意味着只有同名的 alias 具有优先权(技术上也是 shell 关键字,尽管为 shell 关键字命名函数可能不是一个好主意)。

请注意,默认情况下

zsh
确实会扩展脚本中的别名(与
ksh
一样,但不是
bash
),即使您先关闭别名扩展,
type -f
/
whence -f
/
which
仍然如此 首先报告别名。

zsh
中,
-f
选项仅在 zsh 中的查找中包含
 shell 函数,因此 - 除非 
-a
 也用于列出 
all 命令形式 - 将打印给定名称的别名作为唯一的输出。

bash

ksh
 中,
type -f
 实际上 
从查找中排除 函数; whence
 不存在于 
bash
 中,并且在 
ksh
 中不打印函数 
definitionwhich
 不是 
ksh
bash
 中的内置函数,根据定义,外部实用程序无法打印 shell 函数。


9
投票
如果您不太确定要查找什么,您可以直接输入

functions

它会显示所有定义的功能。

请注意,有时它们有很多,因此您可能需要通过管道传输到寻呼机程序:

functions | less

要取消定义函数,请使用

unfunction functionname
    
© www.soinside.com 2019 - 2024. All rights reserved.