Macos – Solve bash script without goto

bashmacos

I have a bash script that I want to do something like

read one_thing
read another_thing

And then it runs some code to see if another_thing is available or already taken, and if it is taken, it should warn the user and again run

read another_thing

so we can have a new value, leaving one_thing undisturbed. Since there's no goto in bash, I'm wondering how to do that. My best guess so far is that maybe I should wrap read another_thing inside a function, so that if needed, it will just call itself, but I feel there must be a “cleaner” way to do it. I'm looking for suggestions on efficient ways to do it.

Best Answer

You can check for your condition in a loop, and break out of it when it’s met.

#!/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
Related Question