Sanjan Grero
Sanjan Grero

Reputation: 327

Using compound conditions in a Bash shell script

I want to do something like below in Bash script. How do I implement it in Bash syntax?

if !((a==b) && (a==c))
then
    # Do something
end if

Upvotes: 15

Views: 30611

Answers (3)

SiegeX
SiegeX

Reputation: 140297

#!/bin/bash

a=2
b=3
c=4

if ! (( (a == b) && (a == c) )); then
  # stuff here
fi

You could also use the following which I personally find more clear:

#!/bin/bash

a=2
b=3
c=4

if (( (a != b) || (a != c) )); then
  # stuff here
fi

Technically speaking, you don't need the parentheses around the sub expressions since the equality operators == != have higher precedence than both the compound comparison operators && ||, but I think it's wise to keep them in there to show the intent, if nothing else.

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 359985

For numeric comparison, you can do:

if ! (( (a == b) && (a == c) ))

For string comparison:

if ! [[ "$a" == "$b" && "$a" == "$c" ]]

In Bash, the double parentheses set up an arithmetic context (in which dollar signs are mostly optional, by the way) for a comparison (also used in for ((i=0; i<=10; i++)) and $(()) arithmetic expansion) and is used to distinguish the sequence from a set of single parentheses which creates a subshell.

This, for example, executes the command true and, since it's always true it does the action:

if (true); then echo hi; fi 

This is the same as

if true; then echo hi; fi

except that a subshell is created. However, if ((true)) tests the value of a variable named "true".

If you were to include a dollar sign, then "$true" would unambiguously be a variable, but the if behavior with single parentheses (or without parentheses) would change.

if ($true)

or

if $true

would execute the contents of the variable as a command and execute the conditional action based on the command's exit value (or give a "command not found" message if the contents aren't a valid command).

if (($true)) 

does the same thing as if ((true)) as described above.

Upvotes: 28

wilhelmtell
wilhelmtell

Reputation: 58677

if [ "$a" != "$b" -o "$a" != "$c" ]; then
  # ...
else
  # ...
fi

Upvotes: 6

Related Questions