如何在Bourne shell中导出函数?

问题描述 投票:7回答:2

是否可以在Bourne shell(sh)中导出函数?

this question的答案表明如何为bashkshzsh这样做,但没有人说sh是否支持它。

如果sh绝对不允许,我将不再花费更多时间来搜索它。

bash function shell unix sh
2个回答
12
投票

不,这是不可能的。

The POSIX spec for export非常清楚它只支持变量。 typeset和在最近的shell中用于此目的的其他扩展只是 - 扩展 - 在POSIX中不存在。


0
投票

不.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
© www.soinside.com 2019 - 2024. All rights reserved.