访问函数文档

访问函数文档

有没有办法在 Bash 中访问文档字符串?如何在 Bash 的函数定义中包含文档字符串?

更具体地说,如何向以下函数添加和访问文档字符串?

    funky() {
    echo "Violent and funky!"
    }

答案1

尽管不是最优的,但以下方法在紧要关头效果很好:

declare -A fundocs_;
doc() { fundocs_[$1]=$2; }
help_doc() { echo "$1:  ${fundocs_[$1]}"; }

doc hi_from_fun "Send a short greeting"
hi_from_fun() { echo "Hi there"; }

help_doc hi_from_fun

将打印文档如下:

hi_from_fun:  Send a short greeting

请注意,第一个参数必须与函数名称匹配,这使得此方法容易出错。为了避免长期出现错误,可以在函数体内定义函数的文档,如下所示:

docd() { :; }  # dummy function
# for debug trap based documentation, redefined later
#  should be called with documentation as arguments
#  near the top of function body

fun2() {
    echo "Hi, I'm fun2 without documentation, just doing my job."; }

fun3() {
    docd "says hi3"
    echo "Hi, I'm fun3 with documentation, doing useful work." ; }

fun4() {
    docd "says hi4"
    echo "hi from fun4 doing other useful work"; }

可以使用临时 DEBUG 陷阱来访问文档字符串,如下所示:

docd_() {
    # process args as documentation string
    # and return from nth level caller
    local n=${1:-2}; shift; local c=${FUNCNAME[$n]}
    local f=${1:-'echo $c: $@'}; shift
    [ -n "$c" -a "$c" != source ] && {
        eval $f
        trap "trap - DEBUG; return 2" DEBUG; } }

pdoc() {  #  redefine docd to call docd_ defined above
    docd() {
        docd_ 2 "" $@
        # default action: echo "function_name:  document_string"
    }

    for f; do $f; done  # arguments are function names

    docd() { : # so that the next call to function runs normally
    }
 }

这样

pdoc fun1 fun4 fun2 docd_ fun3

将打印:

bash: fun1: command not found
fun4: says hi4
Hi, I'm fun2 without documentation, just doing my job.
fun3: says hi3

您可能希望捕获数组中的文档以构建菜单。例如:

prepdoc() {  # collect documentation of functions
    declare -Ag fundocs_
    docd() { docd_ 2 "fundocs_[\$c]=\"\$*\"" $@; }
    for f; do $f; done
    docd() { :; }
    declare -p fundocs_; }

prepdoc fun1 fun4 fun2 docd_ fun3

将打印:

bash: fun1: command not found
Hi, I'm fun2 without documentation, just doing my job.
declare -A fundocs_='([fun3]="says hi3" [fun4]="says hi4" )'

其中不存在的 fun1 和未记录的 fun2 是例外,通常应在扫描期间避免,但在上面包含这些只是为了演示调用时会发生什么。

最后,验证每个功能是否可以正常工作:

for f in fun1 fun4 fun2 docd_ fun3; do $f; done

并将打印:

bash: fun1: command not found
hi from fun4 doing other useful work
Hi, I'm fun2 without documentation, just doing my job.
Hi, I'm fun3 with documentation, doing useful work.

答案2

如果你的意思是“Bash 相当于 Python 的文档字符串”,恐怕我不得不让你失望了,因为根本没有这样的东西。

然而..我必须说实现相当于“文档字符串”功能做一个非常有趣的家庭作业,以学习 Bash 的可编程完成工具以及如何覆盖内置命令,例如help显示此类“文档字符串”或正常的内置命令help的输出。

相关内容