goto: command not found code example
Example 1: bash jump to
#!/bin/bash
function jumpto
{
label=$1
cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
eval "$cmd"
exit
}
start=${1:-"start"}
jumpto $start
start:
x=100
jumpto foo
mid:
x=101
echo "This is not printed!"
foo:
x=${x:-10}
echo x is $x
Example 2: bash jump to
#!/bin/bash
function goto
{
label=$1
cmd=$(sed -n "/^:[[:blank:]][[:blank:]]*${label}/{:a;n;p;ba};" $0 |
grep -v ':$')
eval "$cmd"
exit
}
apt update
start=${1:-"start"}
goto "$start"
: start
goto_msg="Starting..."
echo $goto_msg
goto "continue"
: skipped
goto_msg="This is skipped!"
echo $goto_msg
: continue
goto_msg="Ended..."
echo "$goto_msg"
goto update