是否可以在Bourne shell(sh)中导出函数?
this question的答案表明如何为bash
,ksh
和zsh
这样做,但没有人说sh
是否支持它。
如果sh
绝对不允许,我将不再花费更多时间来搜索它。
不,这是不可能的。
The POSIX spec for export非常清楚它只支持变量。 typeset
和在最近的shell中用于此目的的其他扩展只是 - 扩展 - 在POSIX中不存在。
不.export
的POSIX规范缺少bash中存在的-f
,允许导出函数。
(非常详细)的解决方法是将您的函数保存到文件并在子脚本中将其源代码。
script.是:
#!/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.是:
#!/bin/sh --
. "${function_file:?}"
function_to_export
从终端运行script.sh:
[user@hostname /tmp]$ ./script.sh
This function is being run in ./script.sh
This function is being run in ./script2.sh