linux 脚本 goto,bash中是否有“ goto”语句?

斜俊
2023-12-01

对于某些调试或演示需求,它确实可能有用。

我发现Bob Copeland的解决方案http://bobcopeland.com/blog/2012/10/goto-in-bash/优雅:

#!/bin/bash

# include this boilerplate

function jumpto

{

label=$1

cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')

eval "$cmd"

exit

}

start=${1:-"start"}

jumpto $start

start:

# your script goes here...

x=100

jumpto foo

mid:

x=101

echo "This is not printed!"

foo:

x=${x:-10}

echo x is $x

结果是:

$ ./test.sh

x is 100

$ ./test.sh foo

x is 10

$ ./test.sh mid

This is not printed!

x is 101

 类似资料: