Is there a goto statement available in bash on Linux?

LinuxOperating SystemOpen Source

Long story short, Linux’s bash doesn’t have goto statements and no information about the control structures exists in the official documentation. It should also be noted that we can make use of the break and continue statement to achieve the same behaviour that goto statement provides us.

A simple behaviour of the goto can be achieved with a few tweaks and using the simple if condition in bash.

The script will look something like this

# ... Code You want to run here ...

if false; then

# ... Code You want to skip here ...

fi

# ... You want to resume here ...

Another idea is to make use of a bash script that is slightly more complicated, then the one mentioned above but works like a charm.

#!/bin/bash

function goto
{
   label=$1
   cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
   eval "$cmd"
   exit
}
startFunc=${1:-"startFunc"}

goto $startFunc

startFunc:

x=100
goto foo

mid:
x=101
echo "Not printed!"

foo:
x=${x:-10}
echo x is $x

Output

$ ./sample.sh
x is 100
$ ./sample.sh foo
x is 11
$ ./sample.sh mid
Not printed!
x is 101
raja
Published on 31-Jul-2021 12:15:13
Advertisements