Home > other >  Bash does not stop for second `case` statement
Bash does not stop for second `case` statement

Time:12-08

In the following script if I give y once it goes through the whole script. It does not ask for y/n in case of second case $yn in. It only ask for y/n once not twice.

#!/bin/bash

echo -e "\nFirst Step?"

while true; do
    case $yn in
        [Yy]* ) echo "going through first"; break;;
        [Nn]* ) exit;;
        * ) read -p "Please answer yes or no: " yn;;
    esac
done

echo -e "\nSecond Step?"

while true; do
    case $yn in
        [Yy]* ) echo "going through second"; break;;
        [Nn]* ) exit;;
        * ) read -p "Please answer yes or no: " yn;;
    esac
done

How to solve this problem.

CodePudding user response:

Move the read command above the case statement in each loop.

shopt -s nocasematch

printf '\nFirst step\n'

while true; do
    read -p "Please answer yes or no: " yn
    case $yn in
        y* ) echo "going through first"; break;;
        n* ) exit;;
    esac
done


printf '\nSecond step\n'

while true; do
    read -p "Please answer yes or no: " yn
    case $yn in
        y* ) echo "going through second"; break;;
        n* ) exit;;
    esac
done

Alternately, use select: it handles the looping for you, and sets the variable to a known value

PS3="Please answer Yes or No: "
select ans in Yes No; do
    case $ans in
        Yes) echo "going through nth"; break ;;
        No) exit
    esac
done

CodePudding user response:

In the danger of stating the obvious: yn is already set from the first case step, so the second time around there is no need to go to the default case and read the input again.

Just rename the second yn to yn2 or similar.

#!/bin/bash

echo -e "\nFirst Step?"

while true; do
    case $yn in
        [Yy]* ) echo "going through first"; break;;
        [Nn]* ) exit;;
        * ) read -p "Please answer yes or no: " yn;;
    esac
done

echo -e "\nSecond Step?"

while true; do
    case $yn2 in
        [Yy]* ) echo "going through second"; break;;
        [Nn]* ) exit;;
        * ) read -p "Please answer yes or no: " yn2;;
    esac
done
  •  Tags:  
  • bash
  • Related