There is no goto
in bash.
Here is some dirty workaround using trap
which jumps only backwards:)
#!/bin/bash -e
trap '
echo I am
sleep 1
echo here now.
' EXIT
echo foo
goto trap 2> /dev/null
echo bar
Output:
$ ./test.sh
foo
I am
here now.
This shouldn't be used in that way, but only for educational purposes. Here is why this works:
trap
is using exception handling to achieve the change in code flow.
In this case the trap
is catching anything that causes the script to EXIT. The command goto
doesn't exist, and hence throws an error, which would ordinarily exit the script. This error is being caught with trap
, and the 2>/dev/null
hides the error message that would ordinarily be displayed.
This implementation of goto is obviously not reliable, since any non-existent command (or any other error, for that manner), would execute the same trap command. In particular, you cannot choose which label to go-to.
Basically in real scenario you don't need any goto statements, they're redundant as random calls to different places only make your code difficult to understand.
If your code is invoked many times, then consider to use loop and changing its workflow to use continue
and break
.
If your code repeats it-self, consider writing the function and calling it as many times as you want.
If your code needs to jump into specific section based on the variable value, then consider using case
statement.
If you can separate your long code into smaller pieces, consider moving it into separate files and call them from the parent script.