tags:

views:

3791

answers:

2

The following code

number=1
if [[ $number =~ [0-9] ]]
then
  echo matched
fi

works. If I try to use quotes in the regex, however, it stops:

number=1
if [[ $number =~ "[0-9]" ]]
then
  echo matched
fi

I tried "\[0-9\]", too. What am I missing?

Funnily enough, bash advanced scripting guide suggests this should work.

Bash version 3.2.39.

A: 

It looks like you're trying to match a numeric to a string. Try this:

 if [[ "$number" =~ "[0-9]" ]]
Ian Potter
Tried that, doesn't help. Whether $number is in quotes or not doesn't seem to make any difference. In both cases, quoting the regex makes it stop working.
tpk
+11  A: 

It was changed between 3.1 and 3.2. Guess the advanced guide needs an update.

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1. As always, the manual page (doc/bash.1) is the place to look for complete descriptions.

  1. New Features in Bash

snip

f. Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

Sadly this'll break existing quote using scripts unless you had the insight to store patterns in variables and use them instead of the regexes directly. Example below.

$ bash --version
GNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
$ number=2
$ if [[ $number =~ "[0-9]" ]]; then echo match; fi
$ if [[ $number =~ [0-9] ]]; then echo match; fi
match
$ re="[0-9]"
$ if [[ $number =~ $re ]]; then echo MATCH; fi
MATCH

$ bash --version
GNU bash, version 3.00.0(1)-release (i586-suse-linux)
Copyright (C) 2004 Free Software Foundation, Inc.
$ number=2
$ if [[ $number =~ "[0-9]" ]]; then echo match; fi
match
$ if [[ "$number" =~ [0-9] ]]; then echo match; fi
match
Vinko Vrsalovic