
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Goto Statement Availability in Bash on Linux
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
Advertisements