0

I am trying to perform a simple while loop comparing a variable to a string. It fails to load with the error on this line. Error states [: missing `]' and : command not found. My while loop looks like;

mainMenuInput = ""
while ["$mainMenuInput" != "Q" || "$mainMenuInput" != "q"]
do

2 Answers 2

2

There are a couple of errors:

mainMenuInput="" 
while [ "$mainMenuInput" != "Q" ] && [ "$mainMenuInput" != "q" ]

See that variable declaration do need to be like var=value. Otherwise, bash would interpret that you want to perform the var command with = and value as parameters:

mainMenuInput="" 
             ^
             no spaces around =

In the while you need to put spaces around the brackets. Also, note that you need to use && (and) instead of || (or), because otherwise it won't ever exit the while.

while [ "$mainMenuInput" != "Q" ] && [ "$mainMenuInput" != "q" ]
       ^                          ^^                          ^
   space                   it has to be AND               space

In fact, the condition can be rewritten to something like:

while [[ "$mainMenuInput" != [qQ] ]]
Sign up to request clarification or add additional context in comments.

4 Comments

plus -o instead || or -a instead && when used inside []
Thanks, @herby but POSIX recommends the use of && and || with the single bracket notation over -a and -o.
Thanks a lot guys, I didn't know you had to have no spaces around the '=' thanks. Does what i needed it to now thanks. Also @herby using -o did work for displaying the contents for the do thanks.
@Seatter variables are set with var=value expression, without any space around =. Otherwise, bash would interpret that you want to perform the var command with = and value parameters.
0

If you are using bash I think the correct syntax is:

    while [ $variable -ne "q" || $variable -ne "Q" ];

Comments

Your Answer

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