Home > front end >  Exiting "while true; do" loop in shell script prompt
Exiting "while true; do" loop in shell script prompt

Time:07-04

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?

CodePudding user response:

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
  • Related