Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 565
Rob Bednark Avatar asked Jul 13 '12 21:07

Rob Bednark


3 Answers

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.

like image 170
pb2q Avatar answered Nov 12 '22 01:11

pb2q


I've always just used which for this.

like image 30
Thor Avatar answered Nov 12 '22 01:11

Thor


tl;dr

declare -f foo  # works in zsh and bash

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

If you don't mind or prefer including all command forms that exist for a given name in the output:Thanks, Raine Revere.

type -af  # zsh only (works differently in 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 - as opposed to specifically reporting on the operand as a function.

That said, in practice this means that only an alias of the same name takes precedence (and technically also a shell keyword, though naming functions for shell keywords is probably a bad idea anyway).

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.

In zsh, the -f option only includes shell functions in the lookup in zsh, so - unless -a is also used to list all command forms - an alias by the given name would print as the only output.

In bash and ksh, type -f actually excludes functions from the lookup; whence doesn't exist in bash, and in ksh it doesn't print the function definition; which is not a builtin in ksh and bash, and the external utility by definition cannot print shell functions.

like image 23
mklement0 Avatar answered Nov 12 '22 00:11

mklement0