bashnestedfunction-call

Bash. Return two function levels (two nested calls)


I need to know if Bash has some solution for my case. I need after some conditions to do a "double return". I mean, to perform a return of a function and also return the parent function to skip the rest of the code of that parent function.

I know that I can do a conditional using function return values to achieve this. But I'd like to know if in Bash exist something like "break 2" for functions. I don't want if possible to modify the code of the parent function because as you can imagine, in my real script there are dozens of functions and I don't want to modify all of them.

Example:

#!/bin/bash

function sublevelone() {
    echo "sublevelone"
    # Return 2, or break 2 or something :D
}

function main() {
    sublevelone
    echo "This is the part of the code to being avoid executed"
}

main

Solution

  • This is kinda whacky but if you use parentheses to define levelone, it will execute the function in a subshell and then you can exit out of that shell from an inner function. That said, I think it's more appropriate to use return to send back value that you check for in the parent function.

    #!/bin/bash
    
    function leveltwo() {
            echo "two"
            exit
    }
    
    function levelone() (
            echo "one"
            leveltwo
            echo "three"
    )
    
    levelone
    echo "four"
    

    Will print:

    one
    two
    four