Skip to content

Latest commit

 

History

History
93 lines (84 loc) · 1.92 KB

使用declare保存函数定义.org

File metadata and controls

93 lines (84 loc) · 1.92 KB

使用declare保存函数定义

今天才知道原来 declare -f 可以导出函数的定义。以下是bash manual中的部分片段

函数名和定义可以使用内建命令  declare  或  typeset  加上  -f 参数来列出。
如果在 declare 或 typeset 命令中使用 -F  选项将只列出函数名。
函数可以使用内建命令 export 加上 -f 参数导出,使得子 shell 中它们被自动定义。

也就是说,我们可以使用 declare -f 函数名 来输出指定函数的定义。

function test()
{
    local now=$(date)
    echo Now is ${now}
}
declare -f test

若执行 declare -f 时不带任何函数名,则会列出所有函数的定义:

function test1()
{
    echo test1
}

function test2()
{
    echo test2
}
declare -f

我们因此可以定义一个用来保存函数定义的函数

save_function()
{
    while [[ $# > 0 ]];
    do
        date +"* %F.%T $1"
        echo "#+BEGIN_SRC shell"
        declare -f "$1"
        echo "$+END_SRC"
        shift
    done
}
save_function save_function