2012-02-05 16 views
38

बाश में, क्या फ़ंक्शन बॉडी में फ़ंक्शन का नाम प्राप्त करना संभव है? उदाहरण के लिए निम्नलिखित कोड लेना, मैं अपने शरीर में फ़ंक्शन नाम "टेस्ट" प्रिंट करना चाहता हूं, लेकिन "$ 0" फ़ंक्शन नाम के बजाय स्क्रिप्ट नाम का संदर्भ लेता है। तो फ़ंक्शन का नाम कैसे प्राप्त करें?बाश में, क्या फ़ंक्शन बॉडी में फ़ंक्शन का नाम प्राप्त करना संभव है?

#!/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

धन्यवाद, यह वास्तव में मदद करता है। मैं सिर्फ अपने प्रश्न के समाधान से ज्यादा सीखता हूं। जब स्क्रिप्ट विफल हो जाती है तो इस सरणी को कॉलस्टैक मुद्रित करने के लिए उपयोग किया जा सकता है। –

+5

निश्चित रूप से। उस संबंध में, आपको ब्याज के लिए 'BASH_LINENO' की सामग्री भी मिल सकती है। – FatalError

+0

या आप छोटे और समकक्ष $ FUNCNAME का उपयोग कर सकते हैं। –

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 
संबंधित मुद्दे