如何将函数传播到子shell?

dr *_*rry 7 shell function env subshell

Solaris / sh

我在一个文件中定义了一些函数,这些函数通过加载

. ./some_file.sh 
Run Code Online (Sandbox Code Playgroud)

当我开始一个子shell时

sh
Run Code Online (Sandbox Code Playgroud)

我所有的函数定义都丢失了,但是当我这样做时

env
Run Code Online (Sandbox Code Playgroud)

我确实看到了源代码,有没有一种简单的方法可以让它们在我的子 shell 中运行?

小智 12

您可以将函数从 bash传播到 bash子shell:

function greet1 {
  echo "moin, $1"
}
typeset -fx greet1

greet2() {
  echo "servus, $1"
}
typeset -fx greet2

echo "greet1 bob; greet2 alice" | bash
Run Code Online (Sandbox Code Playgroud)

输出:

moin, bob
servus, alice
Run Code Online (Sandbox Code Playgroud)

另请参阅https://docstore.mik.ua/orelly/unix3/upt/ch29_13.htm


Gil*_*il' 8

函数自然地传播到子外壳

greet () {
  echo "hello, $1"
}
( echo "this is a subshell"; greet bob )
Run Code Online (Sandbox Code Playgroud)

但是它们不是也不能传播到独立的 shell 进程,您可以通过以它的名称调用 shell 来启动这些进程。

Bash 有一个扩展来通过 environment 传递函数,但在其他 shell 中没有这样的东西。虽然您可以模拟该功能,但它无论如何都需要在嵌套 shell 中运行代码。您也可以在嵌套的 shell 中获取函数定义。