Learner
Learner

Reputation: 1634

How to use 'AND' condition in 'test' command in bash shell

I am using below command to test the 'AND' condition

[[  "$string1" =~ "not" -a ! "$string1" =~ "$chas" ]] && echo "Hello"

but it is throwing a syntax error

-bash: syntax error in conditional expression
-bash: syntax error near `-a'

I am not getting what the syntax error here is ...

Individual conditions are working but when using and condition (-a) it is throwing error.

Upvotes: 2

Views: 176

Answers (2)

TrueY
TrueY

Reputation: 7610

Test command [[ is different from [. In [[ -a file True if file exists.. Try && for AND bool operator... But the syntax is a bit different. =~ means regex pattern matching and the " not needed around env vars and regex expression.

So this works for me:

[[  $string1 =~ not && ! $string1 =~ $chas ]] && echo "Hello" 

Upvotes: 5

Petr Skocik
Petr Skocik

Reputation: 60058

In bash, with [[, you can do:

[[  "$string1" =~ "not" && ! "$string1" =~ "$chas" ]] && echo "Hello"

or

[[  "$string1" =~ "not" ]] && [[ ! "$string1" =~ "$chas" ]] && echo "Hello"

Upvotes: 2

Related Questions