Search code examples
bashshellloopsgoto

What could be the substitute to handle the flow control of go-to in SHELL script


We do not have any goto statement in bash, hence I used the below function to implement goto for abrupt jump in the code.

Can we handle this condition without using jumpto function?

Based on the solution in this earlier answer to a related question I have the following code:

 #!/bin/bash
    function jumpto
    {
        label=$1
        cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
        eval "$cmd"
        exit
    }
    start="start"
    jumpto $start
start:
while true
do
    for <condition>
     do
        #do something
        for <condition>
        do
        if <condition>
        then
        break 99
        fi
        #do something
        done
    done
 done
   #do something
   #do something 
   #do manythings
    if <condition>
    then
    #do something
    jumpto start
    else
    #do something
    fi

   for <condition>
    do
    #do something
    done

Solution

  • Rather than trying to extend the syntax of the shell to do

    start:
    
    for ...; do
        for ...; do
            ...
        done
    done
    
    if CONDITION; then
        goto start
    else
        SOMETHING
    fi
    

    you may do

    while true; do
        for ...; do
            for ...; do
                ...
            done
        done
    
        if ! CONDITION; then
            SOMETHING
            break
        fi
    done
    

    or

    while true; do
        for ...; do
            for ...; do
                ...
            done
        done
    
        if ! CONDITION; then
            break
        fi
    done
    
    SOMETHING
    

    UPDATE: New code in question:

    start:
    while true; do
        for ...; do
            for ...; do
                if ...; then
                    break 99
                fi
                ...
            done
        done
    done
    
    ...
    
    if CONDITION; then
        SOMETHING
        goto start
    else
        SOMETHING_ELSE
    fi
    
    for ...; do
        ...
    done
    

    To avoid a goto, this may be transformed into

    while true; do
        while true; do
            for ...; do
                for ...; do
                    if ...; then
                        break 99   # change to one less than
                                   # the total depth, to not exit
                                   # outermost loop
                    fi
                    ...
                done
            done
        done
    
        ...
    
        if ! CONDITION; then
            break
        fi
    
        SOMETHING
    done
    
    SOMETHING_ELSE
    
    for ...; do
        ...
    done