如何在终端中打印 shell 函数的代码?

Kyr*_*Kyr 7 zsh function

我正在使用zsh并且在一些 shell 脚本中定义了一些实用程序 shell 函数,其中很少有调用 from ~/.zshrc,所以假设我们不知道这些函数的位置。一个功能是:

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
}
Run Code Online (Sandbox Code Playgroud)

如何打印该shell函数的代码?

我可以想到像这样的搜索和 grep:

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

但这假设我大致知道此处不正确的位置。

jim*_*mij 11

还有就是内置的命令functionszsh用于此目的

functions k.pstree.n
Run Code Online (Sandbox Code Playgroud)

例如在我的preexec功能的情况下:

$ 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 
}
Run Code Online (Sandbox Code Playgroud)

或者使用which 也有利于在,和 中工作。typeset -fp function_namekshbashyash

在 中zsh,函数定义在$functions特殊关联数组中也可用(键是函数名,值是函数体)。

  • @Costas `declare` 特定于 bash,`typeset` 的优点是也可以在 ksh 和 zsh 中使用。 (3认同)