Bash can print a function defintion:
$ bash -c 'y(){ echo z; }; export -f y; export -f'
y ()
{
echo z
}
declare -fx y
However this fails under POSIX Bash, /bin/sh and /bin/dash:
$ bash --posix -c 'y(){ echo z; }; export -f y; export -f'
export -f y
Can a function definition be printed under a POSIX shell?
Best Answer
You can not do it portably. POSIX spec did not specify any way to dump function definition, nor how functions are implemented.
In
bash
, you don't have to export the function to the environment, you can use:(Work in
zsh
)This works even you run
bash
inposix
mode:In
ksh
:(Works in
bash
,zsh
,mksh
,pdksh
,lksh
)In
yash
:This won't work if
yash
enter POSIXly-correct mode:With
zsh
:Note that both
whence -f
,which
,type -f
will report alias first with the same name. You can use-a
to makezsh
report all definitions.POSIXly, you'd have to record your function definition yourself which you could do with:
or a helper function