6

I am using zsh and I have defined few utility shell function in some shell scripts, few of them called from ~/.zshrc, so let's assume that the we don't know the location of these functions. One function is:

function k.pstree.n {
    if [ "$1" != "" ]
    then
        pstree -p | grep -C3 "$1"
    else
        printf "  Please specify the name of the process you want to show!\n"
    fi
}

How can I print the code of that shell function?

I can think of a search & grep like:

find $(pwd) -name "*sh*" -type f -printf "\"%p\"\n" | xargs grep -C5 "k.pstree.n"

but this assumes that I roughly know the location which is not true here.

Any suggestions? Thanks!

  • Following jimmij answer, the bash equivalent and zsh valid is declare -f, answered in stackoverflow. In my case declare -f k.pstree.n. – Kyr Nov 7 '14 at 11:49
10

There is built-in command functions in zsh for this purpose

functions k.pstree.n

For example in case of my preexec function:

$ functions preexec

preexec () {
    local cmd=${1:-}
    cmd=${cmd//\\/\\\\} 
    [[ "$TERM" =~ screen* ]] && cmd="S $cmd" 
    inf=$(print -Pn "%n@%m: %3~") 
    print -n "\e]2;$cmd $inf\a"
    cmd_start=$SECONDS 
}

Or use typeset -fp function_name which has the benefit of also working in ksh, bash and yash.

In zsh, the function definition is also available in the $functions special associative array (the key is the function name, the value the function body).

  • 1
    Another option is typeset -f what basically do the same as functions, but works in bash too. – jimmij Nov 7 '14 at 11:41
  • 1
    typeset is obsolete, use declare instead – Costas Nov 7 '14 at 11:48
  • 1
    A possible problem with the use of typeset/declare in bash is that older versions (<3.2) have stricter naming constraints than allowed in creation of functions: it denies a name containing "." (and other non-alphanums) if you want just that named function shown. – mr.spuratic Nov 7 '14 at 12:01
  • 3
    @Costas declare is specific to bash, typeset has the advantage of also working in ksh and zsh. – Gilles Nov 7 '14 at 23:53
2

you can use which command :

$ which k.pstree.n

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.