Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exiting "while true; do" loop in shell script prompt

My current project on Linux is to make a script that has three options: yes, no and false input. The last one would cause the script to loop back to the question, but with my current method, even the "yes" option loops back to the original statement. I’m incredibly confused as to how I can fix this. Here’s the part of the script I mean:

while true; do read -p "Do you want to run the script now? (Y/N) " yn
    case $yn in
        [Yy]* ) echo "Permission granted, running commands...";;
        [Nn]* ) echo "Operation aborted, exiting..." && exit;;
        * ) echo "Incorrect input detected, exiting...";;
    esac
done
... more code

How can I make the first command execute the rest of the script, while keeping the function of this loop for the last command at hand?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems you want to break out of the loop and execute the "more code" that comes after. That’s what a break command is for.

while true; do read -p "Do you want to run the script now? (Y/N) " yn
    case $yn in
        [Yy]* ) echo "Permission granted, running commands..." && break;;
        [Nn]* ) echo "Operation aborted, exiting..." && exit;;
        * ) echo "Incorrect input detected, exiting...";;
    esac
done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading