[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Confused by =~ behavior with regards to quoting
From: |
Jean Delvare |
Subject: |
Re: [Help-bash] Confused by =~ behavior with regards to quoting |
Date: |
Fri, 17 Oct 2014 15:34:53 +0200 |
Hi Greg, hi Pierre,
On Fri, 17 Oct 2014 08:24:29 -0400, Greg Wooledge wrote:
> On Fri, Oct 17, 2014 at 11:37:47AM +0200, Jean Delvare wrote:
> > I'm am confused by the behavior of the =~ operator with regards to
> > quoting, in particular the right hand side:
>
> Quoted things on the right hand side become string constants, NOT
> regular expressions. Same with == or = (they become string constants
> instead of glob-style patterns).
>
> > $ [[ a =~ "a" ]] ; echo $?
> > 0
>
> You compared the string a and the string a. They are equal.
>
> > $ [[ a =~ "^a" ]] ; echo $?
> > 1
>
> You compared the string a and the string ^a. They are not equal.
Thanks (and to Pierre as well) for the quick reply and clear
explanation.
On Fri, 17 Oct 2014 15:24:56 +0300, Pierre Gaston wrote:
> The relevant bit is "Any part of the pattern may be quoted to force it to
> be matched as a string."
> So, in quotes, the ^ is treated literally and has not special meaning.
It's indeed in the manual page, and I did read that paragraph, but
apparently I stopped reading before that point for some reason. My
bad :-(
On Fri, 17 Oct 2014 08:24:29 -0400, Greg Wooledge wrote:
> The recommendation for people who want to use =~ is to put the regular
> expression into a shell variable, and then use that variable (unquoted)
> on the right hand side.
>
> re='^gibberish$'
> if [[ $foo =~ $re ]]; then ...
Thanks for the suggestion, I'll remember if I ever need it. That being
said, I can't really think, off the top of my head, of a case where
using the regular expression directly would cause problems. My current
code looks like:
[[ "$1" =~ ^[0-9]+$ ]]
(succeeds if $1 is a positive integer) and it works just fine as far as
I can tell.
--
Jean Delvare
SUSE L3 Support