【问题标题】:How to export a function in Bourne shell?如何在 Bourne shell 中导出函数?
【发布时间】:2015-05-28 04:30:18
【问题描述】:

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

this question 中的答案表明如何为bashkshzsh 执行此操作,但没有人说sh 是否支持它。

如果sh绝对不允许,我不会再花时间去找了。

【问题讨论】:

  • 顺便说一句,/bin/sh 在任何远程现代系统上都是 POSIX sh(在 90 年代初定义),而不是 Bourne sh(在 70 年代定义);这适用于 ash、dash 等,它们是 POSIX sh,而不是 Bourne。也就是说,POSIX sh 比 Bourne 更有特色,所以发现 POSIX 中不存在的东西也表明它在 Bourne 中不存在。

标签: bash function shell unix sh


【解决方案1】:

不,这是不可能的。

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

【讨论】:

  • 将其显式添加到more general question 可能很有用
  • 但是可以在一些 Bourne/POSIX shell 兼容的 shell 中导出函数,对吧?
  • @jarno, ... Bourne 和 POSIX 规范确实非常不同——如果你想测试你使用的是哪一个,请尝试使用 ^ 作为管道字符,Bourne 允许但POSIX shell 没有。无论如何 - 您会发现支持导出函数的唯一 POSIX sh 实现是实现标准的大型超集的实现,即。 ksh 及其精神继承者,例如 bash。
【解决方案2】:

没有。 export 的 POSIX 规范缺少 bash 中允许导出函数的 -f

一个(非常冗长的)解决方法是将您的函数保存到一个文件并在子脚本中获取它。

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

从终端运行 script.sh:

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

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2012-03-04
    • 2011-06-12
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多