7

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.

  • I don't think that this exists. This would be the equvialent of a goto, which doesn't exist in bash as far as I know. – polym Jun 30 '14 at 17:00
  • @polym No, BASH doesn't have a goto unfortunately. – psimon Jun 30 '14 at 17:05
4

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
  • Seems interesting... If I got it right, the main point here is the usage of break 100, which returns to the caller loop, not the caller function. – psimon Jul 1 '14 at 6:18
  • 1
    @psimon The point is that break can skip levels whereas return cannot. – Hauke Laging Jul 1 '14 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.