2010-02-04 67 views
11

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

例如:

$ 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,有没有一些方法,使这种功能的脚本可见?

回答

23

尝试

$ export -f myfunc 
父外壳

,以export功能。

+1

现在,我做*不*知道。 – 2010-02-04 12:36:43

+0

@ Andrew:对!有一些答案是无法改进的。 – 2010-02-05 20:46:31

+0

这些事情应该更好地记录 – erjoalgo 2013-10-12 23:17:48

3

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

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

名为/路径/库文件。然后在你的脚本中,源这样的:

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

这也适用,但我注意到${0}需要父母的价值: 如果你不想在你的脚本一堆出口通话也许更有用。

SCRIPT1:

#!/bin/bash 

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

func "1" 
$(. ./script2) 

SCRIPT2:

#!/bin/bash 

func "2" 

输出:

[mymachine]# ./script1 
func 1 
func 2 
相关问题