How to define a function inside another function in Bash?

前端 未结 6 1251
死守一世寂寞
死守一世寂寞 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:57

    Your code should work as written provided you only call the nested function after it's defined.

    As said in another answer, a func(){<...>} statement is an executable statement that defines a name (in the global scope) associated with the function. Just like if you defined a variable.

    So, you can use func2 anywhere in the code after the func2(){<...>} statement has run:

    #func2 not defined
    func1(){
        #not defined
        func2(){<...>}
        #defined
    }
    #not defined
    func1
    #defined
    func3(){
        #only defined if func3 is called after `func2(){<...>}' has run
    }
    

提交回复
热议问题