Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "and" in Bash while loop

Tags:

linux

bash

Okay, essentially this is what the script looks like:

echo -n "Guess my number: " read guess  while [ $guess != 5 ]; do echo Your answer is $guess. This is incorrect. Please try again. echo -n "What is your guess? " read guess done  echo "That's correct! The answer was $guess!" 

What I want to change is this line:

while [ $guess != 5 ]; do 

To something like this:

while [ $guess != 5 and $guess != 10 ]; do 

In Java I know "and" is " && " but that doesn't seem to work here. Am I going about this the right way using a while loop?

like image 800
Smitty Avatar asked Nov 23 '11 08:11

Smitty


People also ask

Can you use && in bash?

The Bash logical (&&) operator is one of the most useful commands that can be used in multiple ways, like you can use in the conditional statement or execute multiple commands simultaneously.

Can I use && in shell script?

&& strings commands together. Successive commands only execute if preceding ones succeed. Similarly, || will allow the successive command to execute if the preceding fails. See Bash Shell Programming.

What does && do in bash?

"&&" is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0). "\" by itself at the end of a line is a means of concatenating lines together.

How do you do a while loop in bash?

There is no do-while loop in bash. To execute a command first then run the loop, you must either execute the command once before the loop or use an infinite loop with a break condition.


2 Answers

There are 2 correct and portable ways to achieve what you want.
Good old shell syntax:

while [ "$guess" != 5 ] && [ "$guess" != 10 ]; do 

And bash syntax (as you specify):

while [[ "$guess" != 5 && "$guess" != 10 ]]; do 
like image 110
Matvey Aksenov Avatar answered Oct 02 '22 08:10

Matvey Aksenov


The [] operator in bash is syntactic sugar for a call to test, which is documented in man test. "or" is expressed by an infix -o, but you need an "and":

while [ $guess != 5 -a $guess != 10 ]; do 
like image 45
thiton Avatar answered Oct 02 '22 10:10

thiton