Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Is there a goto statement available in bash on Linux?
Bash on Linux does not have a built-in goto statement. Unlike languages such as C or BASIC, bash lacks native goto functionality, and no official control structures exist in the bash documentation to provide direct jump capabilities. However, we can simulate goto-like behavior using alternative approaches with break, continue, and conditional statements.
Alternative Approaches to Goto
While bash doesn't support goto directly, there are several ways to achieve similar control flow behavior.
Method 1: Using Conditional Statements
The simplest way to skip code blocks is using if statements with conditions that control execution flow −
# ... Code you want to run here ...
if false; then
# ... Code you want to skip here ...
fi
# ... Code resumes here ...
Method 2: Function-Based Goto Implementation
A more sophisticated approach involves creating a custom goto function that uses sed to extract and execute code after a specified label −
#!/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"
Sample Output
$ ./sample.sh x is 100 $ ./sample.sh foo x is 10 $ ./sample.sh mid Not printed! x is 101
How the Custom Goto Works
The function-based implementation works by −
Label Detection − Uses
sedto find the specified label followed by a colonCode Extraction − Extracts all lines after the label until the end of file
Dynamic Execution − Uses
evalto execute the extracted codeScript Termination − Calls
exitto prevent execution of remaining code
Better Alternatives in Bash
Instead of simulating goto, consider these bash-native approaches −
| Control Structure | Use Case | Example |
|---|---|---|
break |
Exit loops early | for i in {1..10}; do [[ $i -eq 5 ]] && break; done |
continue |
Skip to next iteration | for i in {1..5}; do [[ $i -eq 3 ]] && continue; echo $i; done |
return |
Exit functions | function test() { [[ $1 -eq 0 ]] && return 1; } |
case |
Multi-way branching | case $var in pattern1) cmd1;; pattern2) cmd2;; esac |
Conclusion
While bash lacks native goto support, you can simulate similar behavior using conditional statements or custom functions. However, it's better to use bash's built-in control structures like break, continue, return, and case statements for cleaner, more maintainable code.
