2

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
11
  • 2
    $var != y || $var != n is always true. Anything that isn't y will make the first part true and y will make the second part true. Commented Feb 4, 2015 at 22:47
  • so, how do I make it false then Commented Feb 4, 2015 at 22:51
  • 2
    Think about the logic of what you are trying to test. Do you want $var is not x OR not y? Or do you want $var is not x AND not y? Commented Feb 4, 2015 at 22:56
  • can you talking to me about the difference because now I am a bit confused about what I want it to do.....sorry Commented Feb 4, 2015 at 23:03
  • 1
    Also use ShellCheck on your code. Commented Feb 4, 2015 at 23:48

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.