How to show zsh function definition (like bash “type myfunc”)?

烈酒焚心 提交于 2019-12-03 01:26:50

问题


How do I show the definition of a function in zsh? type foo doesn't give the definition.

In bash:

bash$ function foo() { echo hello; }

bash$ foo
hello

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

In zsh:

zsh$ function foo() { echo hello; }

zsh$ foo
hello

zsh$ type foo
foo is a shell function

回答1:


The zsh idiom is whence, the -f flag prints function definitions:

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

In zsh, type is defined as equivalent to whence -v, so you can continue to use type, but you'll need to use the -f argument:

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

And, finally, in zsh which is defined as equivalent to whence -c - print results in csh-like format, so which foo will yield the same results.

man zshbuiltins for all of this.




回答2:


I've always just used which for this.




回答3:


tl;dr

declare -f foo  # works in zsh and bash

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

type -f / whence -f / which are suboptimal in this case, because their purpose is to report the command form with the highest precedence that happens to be defined by that name (unless you also specify -a, in which case all command forms are reported) - as opposed to specifically reporting on the operand as a function.

The -f option doesn't change that - it only includes shell functions in the lookup.

Aliases and shell keywords have higher precedence than shell functions, so, in the case at hand, if an alias foo were also defined, type -f foo would report the alias definition.

Note that zsh does expand aliases in scripts by default (as does ksh, but not bash), and even if you turn alias expansion off first, type -f / whence -f / which still report aliases first.




回答4:


If you're not quite sure what you are looking for, you can type just

functions

and it will show you all the defined functions.

Note that there are sometimes a LOT of them, so you might want to pipe to a pager program:

functions | less

to undefine a function, use

unfunction functionname


来源:https://stackoverflow.com/questions/11478673/how-to-show-zsh-function-definition-like-bash-type-myfunc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!