I'm working with Bash 3, and I'm trying to form a conditional. In C/C++, its dead simple: ((A || B) && C)
. In Bash, its turning out not so (I think the Git authors must have contributed this code before they moved onto other endeavors).
This does not work. Note that <0 or 1>
is not a string literal; it means a 0 or 1 (generally comes from grep -i
).
A=<0 or 1>
B=<0 or 1>
C=<0 or 1>
if [ [ "$A" -eq "0" ] || [ "$B" -ne "0" ] ] && [ "$C" -eqe "0" ]; then ... fi
It results in:
line 322: syntax error near unexpected token `[['
I then tried:
A=<0 or 1>
B=<0 or 1>
C=<0 or 1>
if [ ([ "$A" -eq "0" ]) || ([ "$B" -ne "0" ]) ] && [ "$C" -eq "0" ]; then ... fi
it results in:
line 322: syntax error near unexpected token `[['
Part of the problem is search results are the trivial examples, and not the more complex examples with compound conditionals.
How do I perform a simple ((A || B) && C)
in Bash?
I'm ready to just unroll it and repeat the same commands in multiple blocks:
A=<0 or 1>
B=<0 or 1>
C=<0 or 1>
if [ "$A" -eq "0" ] && [ "$C" -eq "0" ]; then
...
elif [ "$B" -ne "0" ] && [ "$C" -eq "0" ]; then
...
fi
[[ … ]]
was added in bash 2.02.((…))
was added in bash 2.0. – Gilles 'SO- stop being evil' Jun 17 '16 at 18:10||
and&&
change from[
to[[
and((
. Equal precedence in[
(use parenthesis to control the order of evaluation), but && has higher precedence in[[
and((
than||
(as in C). – Jun 18 '16 at 03:16[[ … ]]
or$((…))
are just for grouping. – Gilles 'SO- stop being evil' Mar 04 '20 at 17:23if ([ $A -eq 0 ] || [ $B -ne 0 ]) && [ $C -ne 0 ];
: What is wrong with using () instead of {}, so we don't need the semi-colon. How is using a subshell a problem ? – bob dylan Mar 07 '21 at 10:21