nullByteMe
nullByteMe

Reputation: 6391

While loop in shell script says [: too many arguments

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.

Upvotes: 0

Views: 3784

Answers (1)

cmc
cmc

Reputation: 2101

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

Upvotes: 1

Related Questions