1
使用declare保存函数定义
source link: https://www.lujun9972.win/blog/2019/07/25/%E4%BD%BF%E7%94%A8declare%E4%BF%9D%E5%AD%98%E5%87%BD%E6%95%B0%E5%AE%9A%E4%B9%89/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
使用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
test () { local now=$(date); echo Now is ${now} }
若执行 declare -f
时不带任何函数名,则会列出所有函数的定义:
function test1() { echo test1 } function test2() { echo test2 } declare -f
test1 () { echo test1 } test2 () { echo test2 }
我们因此可以定义一个用来保存函数定义的函数
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
* 2019-07-25.18:42:09 save_function #+BEGIN_SRC shell save_function () { while $# > 0 ; do date +"* %F.%T $1"; echo "#+BEGIN_SRC shell"; declare -f "$1"; echo "$+END_SRC"; shift; done } $+END_SRC
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK