user16715270
user16715270

Reputation:

How does bash handle operator precedence

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

Upvotes: 1

Views: 1225

Answers (2)

jhnc
jhnc

Reputation: 16762

  • a || b - execute b if and only if a exited with non-zero status (i.e. fail/false)
  • a && b - execute b if and only if a exited with zero status (i.e. success/true)

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

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

  1. ls succeeds; operator is && so try second command
  2. ls succeeds; operator is || so skip third command
  3. cumulative status is "true"; operator is && so try fourth command
  4. ls succeeds; operator is || so skip fifth command
  5. cumulative status is "true"; operator is || so skip sixth command
  6. done

Demonstration using echo / cd instead of ls / lds:

$ echo ok1 && echo ok2 || cd /fail3 && echo ok4 || echo ok5 || echo ok6
ok1
ok2
ok4
$

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

  1. ls succeeds; operator is && so try second command
  2. lds fails; operator is || so try third command
  3. lds fails; operator is && so skip fourth command
  4. cumulative status is "false"; operator is || so try fifth command
  5. ls succeeds; operator is || so skip sixth command
  6. done

Demonstration:

$ echo ok1 && cd /fail2 || cd /fail3 && echo ok4 || echo ok5 || echo ok6
ok1
bash: cd: /fail2: No such file or directory
bash: cd: /fail3: No such file or directory
ok5
$

Upvotes: 2

P Varga
P Varga

Reputation: 20249

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.

Upvotes: 0

Related Questions