添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I want to have some groups of conditions in a Bash if statement. Specifically, I'm looking for something like the following:

if <myCondition1 and myCondition2> or <myCondition3 and myCondition4> then...

How may I group the conditions together in the way I describe for use with one if statement in Bash?

I did but was unable to find the grouping trick (and didn't know the terminology to search in order to find it). When in doubt, ask. Thanks for the link! – d3pd Feb 19, 2013 at 19:01 I'm not sure this should be marked as a duplicate. The answer to this question specifically addresses grouping conditions, whereas the answer to the duplicate does not. – JoBu1324 Feb 20, 2014 at 17:44 I'm always amazed how easily questions can be marked as duplicates when they are clearly not. This question is about grouping conditions. There is nothing in the answers of that other question that actually answers this one. – Calimo Oct 5, 2016 at 8:56

Use the && (and) and || (or) operators:

if [[ expression ]] && [[ expression ]] || [[ expression ]] ; then

They can also be used within a single [[ ]]:

if [[ expression && expression || expression ]] ; then

And, finally, you can group them to ensure order of evaluation:

if [[ expression && ( expression || expression ) ]] ; then
                IMO this is a clearer answer than the "duplicate". In the third example, make sure to use double brackets - [[ ]]
– JoBu1324
                Feb 20, 2014 at 17:58
                For those who care about compatibility with other shell types, I'll note that doing the above does not appear to work with single brackets [].
– Seldom 'Where's Monica' Needy
                Jul 7, 2016 at 2:50
                Be aware that in the first example, the && and || are the shell's pipeline operators.  In the second and third examples, they are operators handled by the [[...]] conditional command parser.  The first works on exit values of zero and non-zero, the rest work on return values of true and false.  While all of the examples work, they work for different reasons.
– Ti Strga
                Mar 13, 2017 at 17:29
                this question answers me.  I wanted to know if it was possible to group using braces, then add  more conditions after the group.  This demonstrates that use unix.stackexchange.com/questions/290146/… .
– blamb
                Sep 21, 2018 at 22:27
                and how can you break down a long line (e.g. more than 80 chars) of several conditions?  Line-continuation `` and then newline after a logical operator where it makes sense to?
– tarabyte
                Aug 4, 2021 at 17:47