Bash

訪問函式文件

  • May 10, 2021

有沒有辦法在 Bash 中訪問文件字元串?如何在 Bash 中的函式定義中包含文件字元串?

更具體地說,如何向以下函式添加和訪問文件字元串?

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

如果您的意思是“Bash 相當於 Python 的文件字元串”,恐怕我不得不讓您失望,因為沒有這樣的東西。

但是..我必須說,實現“文件字元串”功能的等效功能成為一項非常有趣的作業,以便學習 Bash 的可程式完成功能以及如何覆蓋內置命令,例如help顯示此類“文件字元串”或正常的 builtinhelp的輸出。

雖然次優,但以下方法在緊要關頭可以正常工作:

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.

引用自:https://unix.stackexchange.com/questions/511073