什么可以替代SHELL脚本中处理go-to的流量控制

时间:2016-08-10 11:36:04

标签: bash shell loops goto

我们在bash中没有任何goto语句,因此我使用下面的函数来实现代码中突然跳转的goto

我们可以在不使用jumpto函数的情况下处理这种情况吗?

根据this earlier answer to a related question中的解决方案,我有以下代码:

 #!/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

2 个答案:

答案 0 :(得分:3)

而不是试图扩展shell的语法来做

start:

for ...; do
    for ...; do
        ...
    done
done

if CONDITION; then
    goto start
else
    SOMETHING
fi
你可以做

while true; do
    for ...; do
        for ...; do
            ...
        done
    done

    if ! CONDITION; then
        SOMETHING
        break
    fi
done

while true; do
    for ...; do
        for ...; do
            ...
        done
    done

    if ! CONDITION; then
        break
    fi
done

SOMETHING

更新:有问题的新代码:

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

为了避免转到,可以将其转换为

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

答案 1 :(得分:0)

如果您的目标只是从头开始重新启动脚本,则可以使用exec

#!/bin/bash

lots
of
code
:
if condition; then
  exec "$0" "$@"
fi

如果只有一个,你可以实现一个粗选项跳转到标签。

#!/bin/bash

if [ $1 = '--restart' ]; then
    shift
    # Skip everything in else clause
else
    lots
    more
    code
    :
fi
# :start
lots
of
code
still
:
if condition; then
  exec "$0" --restart "$@"
fi