Monday, January 31, 2022

[SOLVED] Bash does not stop for second `case` statement

Issue

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.


Solution

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


Answered By - glenn jackman
Answer Checked By - Willingham (WPSolving Volunteer)