0

My first bash script; working well except for this line:

# MAINTENANCE MODE ON
while true; do
read -p "TURN ON MAINTENANCE? (Y/N)" yn
case $yn in
    [Yy]* ) sudo /root/Nginx-Maintenance-Mode/maintenance.sh example.com on;;
    [Nn]* ) break;;
    * ) echo "Please answer yes or no.";;
esac
done

This works but after running the command it is asking me the same question again; I don't know why.

Sam
  • 1,557
  • 3
  • 26
  • 51
  • 1
    you need `break` after your command in `yY` section, else while "`true`" will keep looping – P.... Sep 16 '20 at 15:02
  • 2
    Does this answer your question? [How do I prompt for Yes/No/Cancel input in a Linux shell script?](https://stackoverflow.com/questions/226703/how-do-i-prompt-for-yes-no-cancel-input-in-a-linux-shell-script) – thanasisp Sep 16 '20 at 15:23

3 Answers3

1

Since you have put your statements of read, switch and your script/command is present in a while loop which will run so it will be keep running until/unless you place a break inside your yes condition. So kindly do add the same and it should work then.

May be you are looking for following.

cat script.ksh    
while true; do
read -p "TURN ON MAINTENANCE? (Y/N)" yn
case $yn in
    [Yy]* ) echo "Entered yes here..."
            ;&
    [Nn]* ) echo "You entered no here..."
            break;;
    * )     echo "Please answer yes or no."
esac
done

Lets see how it runs and goes:

./script.ksh
TURN ON MAINTENANCE? (Y/N)test
Please answer yes or no.
TURN ON MAINTENANCE? (Y/N)no
You entered no here...
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 1
    In this case, since the OP's `[Nn]` branch is basically a no-op, you can use `;&` to "fall through" to that case from `[Yy]`, rather than duplicate the `break`. – chepner Sep 16 '20 at 15:12
  • @chepner, sure, thank you sir added it now, I hope I did it fine, cheers. – RavinderSingh13 Sep 16 '20 at 15:20
0

You should add a break after your command like so:

# MAINTENANCE MODE ON
while true; do
read -p "TURN ON MAINTENANCE? (Y/N)" yn
case $yn in
    [Yy]* ) sudo /root/Nginx-Maintenance-Mode/maintenance.sh example.com on; break;;
    [Nn]* ) break;;
    * ) echo "Please answer yes or no.";;
esac
done
badew
  • 26
  • 2
0

One option is to loosen your requirement to enter an explicit no. Y or y will turn on maintenance mode. Any other response, whether N or a seemingly invalid response, will do nothing.

# MAINTENANCE MODE ON
read -p "TURN ON MAINTENANCE? (Y/N)" yn
case $yn in
    [Yy]* ) sudo /root/Nginx-Maintenance-Mode/maintenance.sh example.com on;;
esac
chepner
  • 497,756
  • 71
  • 530
  • 681