2012-02-05 22 views
38

在BASH中,是否可以在函數體中獲取函數名?以下面的代碼爲例,我想在它的主體中打印函數名稱「Test」,但「$ 0」似乎是指腳本名稱而不是函數名稱。那麼如何獲得函數名?在BASH中,是否可以在函數體中獲取函數名?

#!/bin/bash 

function Test 
{ 
    if [ $# -lt 1 ] 
    then 
     # how to get the function name here? 
     echo "$0 num" 1>&2 
     exit 1 
    fi 
    local num="${1}" 
    echo "${num}" 
} 

# the correct function 
Test 100 

# missing argument, the function should exit with error 
Test 

exit 0 

回答

64

嘗試${FUNCNAME[0]}。該數組包含當前的調用堆棧。引用手冊頁:

FUNCNAME 
      An array variable containing the names of all shell functions 
      currently in the execution call stack. The element with index 0 
      is the name of any currently-executing shell function. The bot‐ 
      tom-most element is "main". This variable exists only when a 
      shell function is executing. Assignments to FUNCNAME have no 
      effect and return an error status. If FUNCNAME is unset, it 
      loses its special properties, even if it is subsequently reset. 
+1

謝謝,這真的有幫助。我學習的不僅僅是我的問題的解決方案。腳本失敗時,可以使用此數組打印調用堆棧。 – 2012-02-05 03:33:41

+5

當然。在這方面,你也可能會發現'BASH_LINENO'的內容值得關注。 – FatalError 2012-02-05 03:35:38

+0

或者您可以使用較短和等效的$ FUNCNAME。 – 2017-10-06 16:34:56

29

的函數的名稱是在${FUNCNAME[ 0 ]} FUNCNAME是包含在調用堆棧的功能的全部名字的數組,所以:

 
$ ./sample 
foo 
bar 
$ cat sample 
#!/bin/bash 

foo() { 
     echo ${FUNCNAME[ 0 ]} # prints 'foo' 
     echo ${FUNCNAME[ 1 ]} # prints 'bar' 
} 
bar() { foo; } 
bar 
相關問題