0

I understand that this is not a duplicate post, since other posts, even though they have covered development patterns, have not dealt with the while clause precisely. There are many examples of using "if", but not "while".

I tried many codes, but my 'while' clause do not work correctly! :\

I am using: CentOS 7x (64-bit) and shell bash

#!/bin/bash
bkp="x"
while [[ "$bkp" != "Y" || "$bkp" != "y" || "$bkp" != "N" ]]
do
   echo $bkp
   read bkp
done
exit 0

When I run:

bash -x ./script
+ bkp=x
+ [[ x != \Y ]]
+ echo x
x
+ read bkp

I can't get out of while loop! :\ The while clause compare doesn't work!

I tried too:

#!/bin/bash
bkp="x"
while [[ "$bkp" != "Y" ]] || [[ "$bkp" != "y" ]]  || [[ "$bkp" != "N" ]]
do
   echo $bkp
   read bkp
done
exit 0

And

#!/bin/bash
bkp="x"
while [ "$bkp" != "Y" -o "$bkp" != "y"  -o "$bkp" != "N" ]
do
   echo $bkp
   read bkp
done
exit 0

Another example:

#!/bin/bash
bkp="x"
while [ $bkp != 'Y' -o $bkp != 'y'  -o $bkp != 'N' ]
do
   echo $bkp
   read bkp
done
exit 0

Another example:

#!/bin/bash
bkp="x"
while [[ $bkp != 'Y' ]] || [[ $bkp != 'y' ]] || [[ $bkp != 'N' ]]
do
   echo $bkp
   read bkp
done
exit 0

In the last case, when I run the script:

bash -x ./script 
+ bkp=x
+ '[' x '!=' Y -o x '!=' y -o x '!=' N ']'
+ echo x
x
+ read bkp
Y
+ '[' Y '!=' Y -o Y '!=' y -o Y '!=' N ']'
+ echo Y
Y
+ read bkp
y
+ '[' y '!=' Y -o y '!=' y -o y '!=' N ']'
+ echo y
y
+ read bkp
N
+ '[' N '!=' Y -o N '!=' y -o N '!=' N ']'
+ echo N
N
+ read bkp

I imagine that is a simple thing to fix my code, hehehe ...

Any idea?

Thanks, Joca.

Jocalinux
  • 1
  • 2
  • I'm assuming you want `while ! [[ $bkp = [YyNn] ]]; do read -r bkp; done`? – Charles Duffy Jul 13 '18 at 23:08
  • BTW, `-o` and `-a` are marked obsolescent in the POSIX test standard; search for `OB` in http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Jul 13 '18 at 23:09
  • 1
    Or you want `[[ "$foo" != "A" && "$foo" != "B" ]]` – kvantour Jul 13 '18 at 23:09
  • @CharlesDuffy Thanks a lot for your answer, but more and less. How do I compare two variables in the same while? In your example, you compare values ​​of the same variable. How to compare var1 or var2 in the same while? I had searched how to use where clause here in StackOverflow, and what I found was this link: https://stackoverflow.com/questions/15534595/bash-scripting-multiple-conditions-in-while-loop – Jocalinux Jul 13 '18 at 23:40
  • kvantour, Thanks a lot for your help too: #!/bin/bash foo="a" foo2="a" while [[ "$foo" != "A" || "$foo2" != "B" ]] do echo $foo ; echo $foo2 read foo read foo2 done exit 0 Is this! ;) – Jocalinux Jul 13 '18 at 23:46
  • @Jocalinux The problem isn't what you're comparing, the problem is using local OR when you want logical AND. The results of combining negated tests can be counterintuitive; see [de Morgan's Laws](https://en.wikipedia.org/wiki/De_Morgan's_laws). – Gordon Davisson Jul 14 '18 at 00:06

0 Answers0