【问题标题】:Bash - How to call a function declared in a parent shell?Bash - 如何调用在父 shell 中声明的函数?
【发布时间】:2010-02-04 12:07:12
【问题描述】:

我正在编写一个调用父 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,有什么方法可以使该函数对脚本可见吗?

【问题讨论】:

    标签: bash unix shell


    【解决方案1】:

    试试

    $ export -f myfunc
    

    在父shell中,到export函数。

    【讨论】:

    • @Andrew:对!有些答案无法改进。
    • 这些事情应该更好地记录在案
    【解决方案2】:

    @OP,通常您会将每个脚本使用的函数放在一个文件中,然后将它的源代码放入您的脚本中。例如,保存

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

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

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

    【讨论】:

      【解决方案3】:

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

      脚本1:

      #!/bin/bash
      
      func()
      {
        echo func "${1}"
      }
      
      func "1"
      $(. ./script2)
      

      脚本2:

      #!/bin/bash
      
      func "2"
      

      输出:

      [mymachine]# ./script1
      func 1
      func 2
      

      【讨论】:

        猜你喜欢
        • 2012-11-15
        • 2023-03-09
        • 2021-11-05
        • 2014-02-02
        • 2012-10-30
        • 1970-01-01
        • 2010-11-29
        • 2012-07-22
        • 2021-04-21
        相关资源
        最近更新 更多