0

I'm trying to run a very simple script that reads input from a user and continuously loop a question if the users input doesn't match what is expected.

It's being execute via bash:

echo "Specify a directory [Y/N]?"

read ans
while [ [ "$ans" != "Y" ] || [ "$ans" != "y" ] || [ "$ans" != "N" ] || [ "$ans" != "n" ] ]
do
    echo "$ans is not valid, please answer [Y/N]"
    read ans
done

code continues....

Any idea why this is not working? It seems like a pretty straight forward loop.

2
  • 1
    You cannot nest [...] expressions inside each other. Commented Apr 1, 2013 at 17:47
  • 1
    To add to @chepner's comment - if you really do need grouping (in this case you don't - see Clement Rey's answer below), you need to use ( and ) instead (possibly with appropriate escaping/quoting, depending on your exact syntax). Commented Apr 1, 2013 at 17:50

1 Answer 1

1

That should work:

echo "Specify a directory [Y/N]?" 
read ans 
while [ "$ans" != "Y" ] && [ "$ans" != "y" ] && [ "$ans" != "N" ] && [ "$ans" != "n" ]
do
    echo "$ans is not valid, please answer [Y/N]"
    read ans 
done

There were a few mistakes:

  • you were probably thinking AND instead of OR
  • there is no global [ ] for a multiconditionnal while loop
Sign up to request clarification or add additional context in comments.

3 Comments

That allows my program to proceed without the endless loop but I still get the "[: too many arguments" error. "
&& is the correct operator to use here, as $ans will always be unequal to one of the choices.
With ||, he is going in no matter what so I guess he wanted a &&.

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.