Bash - 如何调用父shell中声明的函数?

时间:2010-02-04 12:07:12

标签: bash unix shell

我正在编写一个调用父shell中声明的函数的bash脚本,但它不起作用。

例如:

$ function myfunc() { echo "Here in myfunc" ; }
$ myfunc
Here in myfunc
$ cat test.sh 
#! /bin/bash

echo "Here in the script"
myfunc
$ ./test.sh 
Here in the script
./test.sh: line 4: myfunc: command not found
$ myfunc
Here in myfunc

正如您所看到的,脚本./test.sh无法调用函数myfunc,是否有某种方法可以使该函数对脚本可见?

3 个答案:

答案 0 :(得分:25)

尝试

$ export -f myfunc

在父shell中,export函数。

答案 1 :(得分:3)

@OP,通常你会将每个脚本使用的函数放在一个文件中,然后在你的脚本中找到它。例如,保存

function myfunc() { echo "Here in myfunc" ; }

在名为/ path / library的文件中。然后在你的脚本中,像这样来源:

#!/bin/bash
. /path/library
myfunc

答案 2 :(得分:0)

这也有效但我注意到${0}取父亲的价值: 如果您不想在脚本中进行大量导出调用,可能会更有用。

SCRIPT1:

#!/bin/bash

func()
{
  echo func "${1}"
}

func "1"
$(. ./script2)

SCRIPT2:

#!/bin/bash

func "2"

输出:

[mymachine]# ./script1
func 1
func 2