从子进程调用 bash 函数

Sah*_*has 7 bash subprocess

我不确定是否可能,但我正在寻找一种从其子进程调用 bash 函数的方法。它可能是这样的:

function testfunc() { echo test function; }
bash -c 'testfunc'
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,但是有什么办法可以实现这样的目标吗?

非常感谢您的帮助!

msw*_*msw 6

$ function blargh () {
> echo $1
> }
$ export -f blargh
$ bash
$ blargh hi there
hi
$ exit
$ bash -c "blargh hi there"
hi
Run Code Online (Sandbox Code Playgroud)

export -f是不明显的一点。

$ help export
export: export [-fn] [name[=value] ...] or export -p
    Set export attribute for shell variables.

    Marks each NAME for automatic export to the environment of subsequently
    executed commands.  If VALUE is supplied, assign VALUE before exporting.

    Options:
      -f    refer to shell functions
    ...
Run Code Online (Sandbox Code Playgroud)