user3777083
user3777083

Reputation: 21

Bash if statement with logical OR

I want the commands to execute only when the string variables are not equal to foo or any word starting with bar.

if [[ $string != "foo" || $string != bar* ]]; then
commands
fi

When $string=foo and I use the following code it works fine and no commands execute:

if [[ $string != "foo" ]]; then
commands
fi

but when I add the second part with the || the commands execute when they should not.

Upvotes: 2

Views: 12922

Answers (1)

RichieHindle
RichieHindle

Reputation: 281485

You need an and, not an or:

 if [[ $string != "foo" && $string != bar* ]] ...

What your code is saying is that "it must be true that either the string is not equal to foo, or the string does not start with bar" - that's true for all strings.

What you need to say is "it must be true that the string is not equal too foo, and the string does not start with bar".

(You might want to put double-quotes around $string as well, if there's a chance it could be empty.)

Upvotes: 7

Related Questions