Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export a function in Bourne shell?

Is it possible to export a function in Bourne shell (sh)?

The answers in this question indicate how to do so for bash, ksh and zsh, but none say whether sh supports it.

If sh definitely does not allow it, I won't spend any more time searching for it.

like image 927
anol Avatar asked Mar 24 '15 18:03

anol


2 Answers

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.

like image 199
Charles Duffy Avatar answered Oct 19 '22 14:10

Charles Duffy


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
like image 25
Harold Fischer Avatar answered Oct 19 '22 12:10

Harold Fischer