4

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?

2
  • 2
    Your syntax for [[ is incorrect. Commented Feb 28, 2012 at 14:39
  • 1
    You have to execute the script using bash, not sh (which usually is (d)ash). There is no =~ operator using the test utility (which is being used by (d)ash). Commented Feb 28, 2012 at 14:49

1 Answer 1

10

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

Try:

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

and check bash's man page.

Sign up to request clarification or add additional context in comments.

7 Comments

note, /usr/bin/[ is not part of bash, and its special syntax is accessible with man test not man bash.
bash does use a built-in [ if it can. (See the test expr part of the bash man page.)
oh, you're right, there is a builtin test command, I did not know it. thanks for pointing it out.
When I search for [[ in the bash manpage, I don't get any matches. What is the difference of [, (, and [[ ?
gnu.org/software/bash/manual/… - [ is an "alias" for test, ( is just a grouping parenthesis, [[ is another form of conditional construct.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.