The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 4,262 other subscribers

linux – Bash: Command grouping (&&, ||, …) – Stack Overflow

Posted by jpluimers on 2020/02/18

Excellent answer at [WayBack] linux – Bash: Command grouping (&&, ||, …) – Stack Overflow by Charles Duffy:

Operator precedence for && and || is strictly left-to-right.

Thus:

pwd; (ls) || { cd .. && ls student/; }  && cd student || cd / && cd ;

…is equivalent to…

pwd; { { { (ls) || { cd .. && ls student/; }; } && cd student; } || cd /; } && cd ; }

…breaking that down graphically:

pwd; {                                      # 1
       {                                    # 2
         { (ls) ||                          # 3
                   { cd .. &&               # 4
                              ls student/;  # 5
                   };                       # 6
         } && cd student;                   # 7
       } || cd /;                           # 8
     } && cd ;                              # 9
  1. pwd happens unconditionally
  2. (Grouping only)
  3. ls happens (in a subshell) unconditionally.
  4. cd .. happens if (3) failed.
  5. ls student/ happens if (3) failed and (4) succeeded
  6. (Grouping only)
  7. cd student happens if either (3) succeeded or both (4) and (5) succeeded.
  8. cd / happens if either [both (3) and one of (4) or (5) failed], or [(7) failed].
  9. cd happens if (7) occurred and succeeded, or (7) occurred and succeeded.

Using explicit grouping operators is wise to avoid confusing yourself. Avoiding writing code as hard to read as this is even wiser.

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.