Reputation: 1828
I'd like to get the function name from within the function, for logging purposes.
KornShell (ksh) function:
foo ()
{
echo "get_function_name some useful output"
}
Is there anything similar to $0
, which returns the script name within scripts, but which instead provides a function's name?
Upvotes: 7
Views: 6581
Reputation: 121
The function below seems to get its name in both Bash and ksh:
# ksh or bash
function foo {
local myname="${FUNCNAME[0]:-$0}"
echo "$myname"
}
# test
foo
# ...
Upvotes: 0
Reputation: 109
Use the ksh "function foo ..." form:
$ cat foo1
#!/bin/ksh
foo3() { echo "\$0=$0"; }
function foo2 { echo "\$0=$0"; }
foo2
foo3
$ ./foo1
$0=foo2
$0=./foo1
Upvotes: 5
Reputation: 109
[...] what are the main pros/cons of using keyword function?
Main pro is that "typeset myvar=abc" inside the function is now a local variable, with no possible side effects outside the function. This makes KSH noticeably safer for large shell scripts. Main con is, perhaps, the non-POSIX syntax.
Upvotes: 5
Reputation: 363787
If you define the function with the function
keyword, then $0
is the function name:
$ function foo {
> echo "$0"
> }
$ foo
foo
(Tested in pdksh.)
Upvotes: 10