How to define a function inside another function in Bash?

前端 未结 6 1239
死守一世寂寞
死守一世寂寞 2020-12-07 16:24

I have the following code

func1(){
    #some function thing
    function2(){
        #second function thing
    }
}

and I want to call

6条回答
  •  庸人自扰
    2020-12-07 16:53

    Limit the scope of the inner function

    Use function defined with parenthesis () instead of braces {}:

    f() (
      g() {
        echo G
      }
      g
    )
    
    # Ouputs `G`
    f
    # Command not found.
    g
    

    Parenthesis functions are run in sub-shells, which have the same semantics of () vs {}, see also: Defining bash function body using parenthesis instead of braces

    This cannot be used if you want to:

    • set variables
    • exit
    • cd

    as those are lost in the created sub-shell.

    See also: bash functions: enclosing the body in braces vs. parentheses

提交回复
热议问题