Bash - How to call a function declared in a parent shell?

后端 未结 3 1219
旧时难觅i
旧时难觅i 2020-12-09 05:16

I am writing a bash script that calls functions declared in the parent shell, but it doesn\'t work.

For example:

$ function myfunc() { echo \"Here in         


        
相关标签:
3条回答
  • 2020-12-09 05:39

    @OP, normally you would put your function that every script uses in a file, then you source it in your script. example, save

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

    in a file called /path/library. Then in your script, source it like this:

    #!/bin/bash
    . /path/library
    myfunc
    
    0 讨论(0)
  • 2020-12-09 05:47

    Try

    $ export -f myfunc
    

    in the parent shell, to export the function.

    0 讨论(0)
  • 2020-12-09 05:56

    This also works but I noticed ${0} takes parent's value: Maybe more useful if you don't want to have a bunch of export calls in your scripts.

    script1:

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

    script2:

    #!/bin/bash
    
    func "2"
    

    Output:

    [mymachine]# ./script1
    func 1
    func 2
    
    0 讨论(0)
提交回复
热议问题