using compound conditions in bash shell script
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.
#!/bin/basha=2b=3c=4if ! (( (a == b) && (a == c) )); then # stuff herefi
You could also use the following which I personally find more clear:
#!/bin/basha=2b=3c=4if (( (a != b) || (a != c) )); then # stuff herefi
Technically speaking you don't need the parens around the sub expressions since the equality operators == !=
have higher precedence then both the compound comparison operators && ||
but I think it's wise to keep them in there to show intent if nothing else.