Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash - if return code >=1 re run script, start at the beginning

Tags:

bash

shell

goto

I have a bash script that prints a heading and tests for a value of "Y" or "N".

When someone enters text that does not equal "Y" or "N", I would like to send them back to the beginning of the script, so it prints the heading and the question again.

I know you can do this with goto but I was wondering if there's a different way because I hear many individuals say you should not use goto or that it is deprecated. Whether true or not, I'd like to see if anyone else has a way to solve this problem.

Thanks in advance.

like image 721
jonschipp Avatar asked Feb 23 '23 13:02

jonschipp


1 Answers

You could implement it in a loop:

while [ !$exit_loop ]
do
    echo "enter choice - "
    read -n 1 input
    case "$input" in
     y|Y) $exit_loop = 1;;
     n|N) $exit_loop = 1;;
     *) echo "invalid choice";;
    esac
done

Personally I find no difference between using a goto/loop or any other means. I'd always say to use what is most suitable for the situation - for yours, I'd use a goto.

e.g. If you have multiple indentations spanning lots of lines, and you need to jump back to the start of a function, I'd use a goto - it's a lot easier to understand in its context.

like image 144
septical Avatar answered Mar 02 '23 23:03

septical