Getting the function name

Hi,

In order to get the most out of error handling, I'd like to include the function name of where the script is currently at.

I.e.

test_function() {
   echo "Script: $0"
   echo "Function: <a variable that contains test_function>"
}

Is there something like this?

You can assign one variable at the start of the function..

fun_one () {
fun_name="fun_one"
}

Which shell are you using?

What shell do you use? Bash has a special variable FUNCNAME that holds this information.

I'm using kornshell.

Setting a variable at the beginning of each function is not ideal.

$ cat myTest
echo $0

myFunc1() {
  echo $0
}

function myFunc2 {
  echo $0
}

myFunc1
myFunc2
$ ./myTest
./myTest
./myTest
myFunc2

This doesn't work for me:

$ ./myTest
./myTest
./myTest
./myTest
$ ksh ./myTest
./myTest
./myTest
./myTest

In more recent versions of the kornshell 93, there is the variable $.sh.fun which works with both the Posix- and the kornshell function syntax

#!/bin/ksh93

function f1
{
    print I am ${.sh.fun}
}

f2 ()
{
    print I am ${.sh.fun}
}

f1
f2

Output:

I am f1
I am f2

Thanks for all the tips, unfortunately none of them work for me. I think I'll just switch to bash.

Which OS (including version) and version of KSH are you using?

We asked if you could post your script, but you never did.

Probably Solaris <= 10.

Neither /bin/ksh nor /usr/xpg4/bin/sh process $0 in ksh-style functions correctly. Just checked.

I'm sorry, I didn't see that. I don't have a script, I was just testing it with a few small examples.

As for the version, I'm running SunOS 5.10 with ksh version M-11/16/88i.

I've just done a fresh install of Solaris 10, and it seems there is no ksh93 :confused:

Bash does have the $FUNCNAME variable, as said, but that's not a compelling enough reason (for me at least) to switch shells!

So your options appear to be: use Bash; install a newer ksh; set the name at the beginning of the function, as suggested; wait for someone who might know something we don't; write a wrapper:

$ cat myTest
#!/usr/bin/ksh

call() {
  FUNCNAME="$1"; shift
  "$FUNCNAME" "$@"
}

function f1
{
    echo "I am $FUNCNAME with $@ (${#@} arg(s))"
}

f2 ()
{
    echo "I am $FUNCNAME with $@ (${#@} arg(s))"
}

call f1 a b c "d e"
call f2 1 2
$ ./myTest
I am f1 with a b c d e (4 arg(s))
I am f2 with 1 2 (2 arg(s))

That's true. ksh93 was added to Opensolaris by the Korn Shell 93 integration/migration project and is the default kornshell in Solaris 11.

If you want to install ksh93 for Solaris <= 10, you can download prebuilt binaries as well as the source code from here

Ha ha. If I'd read properly where you originally said "<= 10" I could have saved myself the trouble of installing 10. Oh well :smiley:

You could pass $LINENO to your reporting function. At least then you would know from where it was called.

Regards,
Alister