How to export a function in Bourne shell? How to export a function in Bourne shell? shell shell

How to export a function in Bourne shell?


No, it is not possible.

The POSIX spec for export is quite clear that it only supports variables. typeset and other extensions used for the purpose in more recent shells are just that -- extensions -- not present in POSIX.


No. The POSIX specification for export lacks the -f present in bash that allows one to export a function.

A (very verbose) workaround is to save your function to a file and source it in the child script.

script.sh:

#!/bin/sh --function_holder="$(cat <<'EOF'    function_to_export() {        printf '%s\n' "This function is being run in ${0}"    }EOF)"function_file="$(mktemp)" || exit 1export function_fileprintf '%s\n' "$function_holder" > "$function_file". "$function_file"function_to_export./script2.shrm -- "$function_file"

script2.sh:

#!/bin/sh --. "${function_file:?}"function_to_export

Running script.sh from the terminal:

[user@hostname /tmp]$ ./script.shThis function is being run in ./script.shThis function is being run in ./script2.sh