问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/29239806/how-to-export-a-function-in-bourne-shell