POSIX Shell – Print Function Definition

functionposixshell

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:

declare -f funcname

(Work in zsh)

This works even you run bash in posix mode:

$ bash --posix -c 'y(){ echo z; }; declare -f y'
y () 
{ 
    echo z
}

In ksh:

typeset -f funcname

(Works in bash, zsh, mksh, pdksh, lksh)


In yash:

typeset -fp funcname

This won't work if yash enter POSIXly-correct mode:

$ yash -o posixly-correct -c 'y() { ehco z; }; typeset -fp y'
yash: no such command `typeset'

With zsh:

print -rl -- $functions[funcname]
whence -f funcname
type -f funcname
which funcname

Note that both whence -f, which, type -f will report alias first with the same name. You can use -a to make zsh report all definitions.


POSIXly, you'd have to record your function definition yourself which you could do with:

myfunction_code='myfunction() { echo Hello World; }'
eval "$myfunction_code"

or a helper function

defn() {
  code=$(cat)
  eval "${1}_code=\$code; $1() { $code; }"
}

defn myfunction << 'EOF'
echo Hello World
EOF

printf '%s\n' "$myfunction_code"