Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the function name in function body? [duplicate]

Tags:

bash

shell

In BASH, is it possible to get the function name in function body? Taking following codes as example, I want to print the function name "Test" in its body, but "$0" seems to refer to the script name instead of the function name. So how to get the function name?

#!/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 
like image 396
Yun Huang Avatar asked Feb 05 '12 03:02

Yun Huang


People also ask

Can two functions have the same name?

Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.

Is it possible to declare more than one function with the same name?

In a strongly typed language, the parser can (in principle) make the difference between functions with the same name but a different argument list (number and type of the arguments), at function-declaration time as well as function-call time. This is called function overloading and also applies to class methods.

How do you call a function name my function?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.


2 Answers

Try ${FUNCNAME[0]}. This array contains the current call stack. To quote the man page:

   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. 
like image 101
FatalError Avatar answered Oct 07 '22 20:10

FatalError


The name of the function is in ${FUNCNAME[ 0 ]} FUNCNAME is an array containing all the names of the functions in the call stack, so:

 $ ./sample foo bar $ cat sample #!/bin/bash  foo() {         echo ${FUNCNAME[ 0 ]}  # prints 'foo'         echo ${FUNCNAME[ 1 ]}  # prints 'bar' } bar() { foo; } bar 
like image 30
William Pursell Avatar answered Oct 07 '22 19:10

William Pursell