How to define a function inside another function in Bash?

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

    In the question case I suppose that you were trying to call function2 before it is defined, "some function thing" should have been after the function2 definition.

    For the sake of discussion, I have a case where using such definitions can be of some use.

    Suppose you want to provide a function that might be complex, its readability could be helped by splitting the code in smaller functions but you don't want that such functions are made accessible.

    Running the following script (inner_vs_outer.sh)

    #!/bin/bash
    function outer1 {
        function inner1 {
           echo '*** Into inner function of outer1'
        }
        inner1;
        unset -f inner1
    }
    
    function outer2 {
        function inner2 {
           echo '*** Into inner function of outer2'
        }
        inner2;
        unset -f inner2
    }
    export PS1=':inner_vs_outer\$ '
    export -f outer1 outer2
    
    exec bash -i
    

    when executed a new shell is created. Here outer1 and outer2 are valid commands, but inner is not, since it has been unset exiting from where you have outer1 and outer2 defined but inner is not and will not be because you unset it at the end of the function.

    $ ./inner_vs_outer.sh
    :inner_vs_outer$ outer1
    *** Into inner function of outer1
    :inner_vs_outer$ outer2
    *** Into inner function of outer2
    :inner_vs_outer$ inner1
    bash: inner1: command not found
    :inner_vs_outer$ inner2
    bash: inner2: command not found
    

    Note that if you define the inner functions at the outer level and you don't export them they will not be accessible from the new shell, but running the outer function will result in errors because they will try executing functions no longer accessible; instead, the nested functions are defined every time the outer function is called.

提交回复
热议问题