Sandra Schlichting
Sandra Schlichting

Reputation: 25986

Syntax error in [[ conditional expression with bash

When I execute this

regex='^[-a-z0-9]+$'
string='abcd1--'
if [[ $string =~ $regex ] -a ![ grep - "--" ]]
then 
    echo "valid"
else
    echo "not valid"
fi

I get

~$ sh t.sh 
t.sh: line 3: syntax error in conditional expression
t.sh: line 3: syntax error near `]'
t.sh: line 3: `if [[ $string =~ $regex ] -a [ grep - "--" ]]'
~$ 

It is suppose to return not valid.

Can someone figure out what's wrong?

Upvotes: 3

Views: 19274

Answers (1)

Mat
Mat

Reputation: 206679

You're mixing [ and [[ syntax in a strange way.

Try:

if [[ ( $string =~ $regex ) && !( $string =~ "--" ) ]]

and check bash's man page.

Upvotes: 9

Related Questions