haunted85
haunted85

Reputation: 1671

Regex matches from command line, doesn't match from bash script

I'm a bit confused: how come a regular expression works perfectly well using grep from command line and as I use the exactly same regular expression in a bash conditional statement, it doesn't work at all?

I'd like to match all the strings containing letters only, therefore my regular expression is: ^[a-zA-Z]\+$.

Please will you help sort this out?

Here's the snippet from my bash code

if ! [[ "$1" =~ '^[a-zA-z]+$' ]] ; then
    echo "Error: illegal input string." >&2
    exit 1
fi

Upvotes: 0

Views: 3032

Answers (1)

dogbane
dogbane

Reputation: 274592

Don't escape the +.

This works for me:

$ [[ "Abc" =~ ^[a-zA-Z]+$ ]] && echo "it matches"
$ it matches

Also, you don't need single quotes around the regex. The following works for me:

if ! [[ "$1" =~ ^[a-zA-z]+$ ]] ; then
    echo "Error: illegal input string." >&2
    exit 1
fi

Upvotes: 2

Related Questions