Friday, September 06, 2019

Re: Why regex doesn't work in while loop's condition?

On Fri, Sep 06, 2019 at 11:39:06PM +0500, JohnS wrote:
> Hi, all!
>
> Why next construction doesn't work?
>
> read x; while [ "$x" != [abc] ]; do echo "Not a, b or c"; break; done
>
> I tried many variants but can't make it work. Moreover I don't understand WHY it
> doesn't work?!
>
> Thanks!

The shells in the OpenBSD base system do not support matching regular
expressions with that syntax. You may have been thinking of bash,

while [[ ! $x =~ [abc] ]]; do ...; done

Or, in ksh,

while [[ $x != [abc] ]]; do ...; done

Here however, [abc] is not a regular expression, but a filename globbing
pattern, and the test will test for equality rather than trying to match
a substring (as would be the case with a regular expression match).

Note that this test requries [[ ... ]] rather than [ ... ]. See the
ksh(1) manual.

No comments:

Post a Comment