使用 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 [[ https://blog.lujun9972.win/blog/2019/07/25/使用declare保存函数定义/$ ]]; 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 https://blog.lujun9972.win/blog/2019/07/25/使用declare保存函数定义/$ ; do date +"* %F.%T $1"; echo "#+BEGIN_SRC shell"; declare -f "$1"; echo "$+END_SRC"; shift; done } $+END_SRC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论