简体   繁体   English

如何在 Bourne shell 中导出函数?

[英]How to export a function in Bourne shell?

Is it possible to export a function in Bourne shell (sh)?是否可以在 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. 这个问题的答案表明如何为bashkshzsh这样做,但没有人说sh是否支持它。

If sh definitely does not allow it, I won't spend any more time searching for it.如果sh肯定不允许,我就不会再花时间去找了。

No, it is not possible. 不,这是不可能的。

The POSIX spec for export is quite clear that it only supports variables. 用于导出的POSIX规范非常明确,它只支持变量。 typeset and other extensions used for the purpose in more recent shells are just that -- extensions -- not present in POSIX. 在更新的shell中用于此目的的typeset和其他扩展只是 - 扩展 - 在POSIX中不存在。

No. The POSIX specification for export lacks the -f present in bash that allows one to export a function. 不是。用于export的POSIX规范缺少bash中的-f ,允许导出函数。

A (very verbose) workaround is to save your function to a file and source it in the child script. (非常详细)的解决方法是将您的函数保存到文件并在子脚本中将其源代码。

script.sh: 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: script2.sh:

#!/bin/sh --

. "${function_file:?}"

function_to_export

Running script.sh from the terminal: 从终端运行script.sh:

[user@hostname /tmp]$ ./script.sh
This function is being run in ./script.sh
This function is being run in ./script2.sh

Eval it`s eviel, but you can use eval in some cases. eval 这很糟糕,但在某些情况下你可以使用eval Offcourse you should undestand what you do当然你应该明白你在做什么

#myfunc.sh
myfunc()
{
  #do somthing
}
#script.sh
eval "$(cat myfunc.sh)"
myfunc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM