How to export a function in Bourne shell?
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 1
export function_file
printf '%s\n' "$function_holder" > "$function_file"
. "$function_file"
function_to_export
./script2.sh
rm -- "$function_file"
script2.sh:
#!/bin/sh --
. "${function_file:?}"
function_to_export
Running script.sh from the terminal:
[user@hostname /tmp]$ ./script.sh
This function is being run in ./script.sh
This function is being run in ./script2.sh
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.