BASH return to main function

bashfunctionshell-script

I have a BASH script that calls a function, which calls other functions:

#!/bin/bash
function foo
{
    function bar
    {
        # do something
    }
    bar
}
foo

How can I return from bar directly to the main function? The case is that bar handles user input and if it receives a negative answer, it must return to the main function, otherwise it has to return to foo.

Returning to foo is not a problem with a simple return statement. For the other, I tried this (which actually works):

#!/bin/bash
function foo
{
    function bar
    {
        if [negative] # abstract statement
        then return 1
        else return 0
        fi
    }
    ! bar && return
}
foo

But since I have functions like foo spread across the whole project (bar is defined in a header file), is there a way that only requires modification to bar? The project is ~2k lines long and consists of several files, it would be much easier that way if there's a solution.

Best Answer

There is no nice way (I am aware of) to do that but if you are willing to pay the price...

Instead of putting the code in functions you can put it in files you source. If the functions need arguments then you have to prepare them with set:

set -- arg1 arg2 arg3
source ...

Three files:

  1. testscript.sh

    #! /bin/bash
    
    startdir="$PWD"
    
    echo mainscript
    
    while true; do
            echo "begin: helper loop"
            source "${startdir}/func_1"
            echo "end: helper loop"
            break
    done
    
    echo mainscript
    
  2. func_1

    echo "begin: func_1"
    source "${startdir}/func_2"
    echo "end: func_1"
    
  3. func_2

    echo "begin: func_2"
    echo break from func_2
    break 100
    echo "end: func_2"
    

Result:

> ./testscript.sh
mainscript
begin: helper loop
begin: func_1
begin: func_2
break from func_2
mainscript
Related Question