Home > Net >  How does bash handle operator precedence
How does bash handle operator precedence

Time:01-01

I have a problem with bash precedence operators, I can't seem to find a logical way of how bash ordering multi commands whit chain operator.

First command : ls && ls || lds && ls || ls || ls

Second command : ls && lds || lds && ls || ls || ls

How does evaluate the above commands? In a more a general way how bash handle multi command separated by operator

CodePudding user response:

  • a || b - execute b if and only if a exited with non-zero status
  • a && b - execute b if and only if a exited with zero status

Assuming ls always succeeds (zero exit status) and lds always fails (non-zero exit status):

First command : ls && ls || lds && ls || ls || ls

  1. assign: a1 = ls; op1 = && ; b1 = ls || lds && ls || ls || ls
  2. a1 succeeds, so try b1
  3. assign: a2 = ls; op2 = || ; b2 = lds && ls || ls || ls
  4. a2 succeeds, so done

Second command : ls && lds || lds && ls || ls || ls

  1. assign: a1 = ls; op1 = &&; b1 = lds || lds && ls || ls || ls
  2. a1 succeeds, so try b1
  3. assign: a2 = lds; op2 = ||; b2 = lds && ls || ls || ls
  4. a2 fails, so try b2
  5. assign: a3 = lds; op3 = &&; b3 = ls || ls || ls
  6. a3 fails, so done

CodePudding user response:

https://tldp.org/LDP/abs/html/opprecedence.html

In general, && has the same precedence as ||, so they are executed left to right. You can use parentheses though.

  • Related