1

Bash can print the current function name:

$ bash -c 'g(){ echo $FUNCNAME; }; g'
g

However Dash cannot use FUNCNAME:

$ dash -c 'g(){ echo $FUNCNAME; }; g'

It is possible to access the current function name with Dash?

3

With any POSIX shells:

defun() {
  eval "
    $1() {
      FUNCNAME=$1
      $(cat)
    }
  "
}

defun g <<\}
  printf '%s\n' "$FUNCNAME"
}

g

Note that you can't call a function defined by defun inside body of a function defined by defun.

  • You could allow nesting by encoding the function call stack in the FUNCNAME variable, e.g. using / as a separator (I don't think any shell allows slashes in function names). It would be tricky to catch all return statements though, but you could make wrapper functions instead. – Gilles Feb 22 '16 at 22:49
  • (but really, if you want ksh, you know where to find it!) – Gilles Feb 22 '16 at 22:49
  • @Gilles: Good point. I'm on my holiday and don't have time to investigate more. If you don't mind, please making an improvement or providing your own answer. – cuonglm Feb 22 '16 at 23:19
  • 1
    Thank you for the answer, and I have upvoted. However I will not accept because this is an awful workaround. It appears the answer is essentially "Dash cant do it" – Steven Penny Feb 22 '16 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.