Reputation:
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
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
ls
succeeds; operator is &&
so try second commandls
succeeds; operator is ||
so skip third command&&
so try fourth commandls
succeeds; operator is ||
so skip fifth command||
so skip sixth commandDemonstration 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
ls
succeeds; operator is &&
so try second commandlds
fails; operator is ||
so try third commandlds
fails; operator is &&
so skip fourth command||
so try fifth commandls
succeeds; operator is ||
so skip sixth commandDemonstration:
$ 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
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