[GRLUG] Bash regex

Nathan Phillip Brink binki at gentoo.org
Tue May 7 13:26:03 EDT 2013


On Tue, May 07, 2013 at 11:16:29AM -0500, L. V. Lammert wrote:
> Trying to ensure the parameter to a script matches:
> 
> 	YYYY-MM (e.g. 2013-06)
> 
> It would seem this would be the desired pattern:
> 
> if [[ ! $1 =~ '[0-9]{4}-[0-9]{2}' ]] ; then
>    echo '    Usage: backup YYYY-MM'
>    exit
> fi
> 
> However it will not match a valid YYYY-MM. Cluestick, anyone?

See “$ info '(bash)Conditional Constructs'” which, in explaining the
regex “=~” operator, says “Any part of the pattern may be quoted to
force it to be matched as a string.” Your expression works after
removing the single quotes.

It appears that if you want to include spaces in your regex, you must
escape just the spaces with singlequotes or a backslash per whitespace
character. I am not sure if there is a way to quote an entire regex
without getting the “force it to be matched as a string” behavior.

-- 
binki

Look out for missing or extraneous apostrophes!
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://shinobu.grlug.org/pipermail/grlug/attachments/20130507/640931c8/attachment-0001.pgp>


More information about the grlug mailing list