Crisly Domingos
Crisly Domingos

Reputation: 75

checking two conditions using while loop in bash script

I want to check if the user has not entered 'y' or 'n' and if not then to keep looping asking the user to entered the correct letter but it is not working... the code below shows what I have tried so far ....can someone help me please???

echo "Enter 'y' to exit or 'n' to continue" 
echo -n "Do you want to exit? "
read character

while [ "$character" != "y" || "$character" != "n" ];
do

    echo -n "Wrong key re-enter 'y' to exit or 'n' to continue"
    read character
done

Upvotes: 2

Views: 4661

Answers (3)

code
code

Reputation: 4221

This approach tries to account for more user possibilities and still accomplish the same thing.

#if the user's input is not Y or N, Yes or No, y or n, yes or no
while [[ ! "$character" =~ ^([yY][eE][sS]|[yY])$ ]] && [[ ! "$character" =~ ^([nN][oO]|[nN])$ ]]
do
    echo -n "Wrong key re-enter 'y' to exit or 'n' to continue"
    read character
done

Upvotes: 0

Crisly Domingos
Crisly Domingos

Reputation: 75

Thanks a lot to all of you... after a good persistence and resilience I finally found the answer of what I was looking for... A posted the code below:

#if the user's input is not Y or N
while [[ $(read -sn1; echo ${character^^})  =~ [^YN] ]];
do
    echo -n "Re-enter 'y' to exit or 'n'to continue: ?"
    read character
done 

Upvotes: 1

osirisgothra
osirisgothra

Reputation: 2237

you can just:

while [[ $(read -sn1 character; echo ${character^^})  =~ [^YN] ]]; do
  echo -n "Wrong key ..."
done   
  • you'll want -s unless you want the key echoed
  • you will want to have -n1 to limit the input to ONE character
  • you can also check for ctrl+c and ctrl+d pressed via $? (ctrl-d is 1 and ctrl+c is 130, but ctrl+d catching only works if you include the -e flag and use readline)
  • you can include a prompt in there too if you want, and also, you dont have to use '$character' you can just give it nothing and check $REPLY
  • if you really dont want ctrl+c pressed at all consider using a trap

Upvotes: 1

Related Questions