bash jump to


#!/bin/bash
# include this boilerplate
function jumpto
{
    label=$1
    cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
    eval "$cmd"
    exit
}

start=${1:-"start"}

jumpto $start

start:
# your script goes here...
x=100
jumpto foo

mid:
x=101
echo "This is not printed!"

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

3.86
7

                                    #!/bin/bash

read -p 'Input something > ' one_thing

while true; do
  read -p 'Input something else > ' another_thing

  # Write some code to check if the requirements are met
  # Let's say in this case they are when the variable `thing_to_work` equals `done`

  if [[ "${thing_to_work}" == 'abcde' ]]; then
    break # Exit the loop
  else
    echo 'The requirements were not met, so the loop will start again'
  fi
done

3.86 (7 Votes)
0
4.25
8

                                    #!/bin/bash

# BAT / CMD goto function
function goto
{
    label=$1
    cmd=$(sed -n "/^:[[:blank:]][[:blank:]]*${label}/{:a;n;p;ba};" $0 | 
          grep -v ':$')
    eval "$cmd"
    exit
}

apt update

# Just for the heck of it: how to create a variable where to jump to:
start=${1:-"start"}
goto "$start"

: start
goto_msg="Starting..."
echo $goto_msg
# Just jump to the label:
goto "continue"

: skipped
goto_msg="This is skipped!"
echo $goto_msg

: continue
goto_msg="Ended..."
echo "$goto_msg"

# following doesn't jump to apt update whereas original does
goto update

4.25 (8 Votes)
0
3
1
Cristina78 110 points

                                    while :
do
  clear
  echo -n 'Questions? '
  read x
  switch $x in
    a)
      echo a
      ;;
    b|c)
      echo b or c
      ;;
    q)
      break
      ;;
    *)
      echo Invalid command \"$x\"
      ;;
  esac 
done

3 (1 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source