4 ms·
'cmd && do_sth || do_sth_else' is not equivalent to if else https://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3 https://mywiki.wooledge.org/B
by sharley 6y ago
'cmd && do_sth || do_sth_else' is not equivalent to if else
https://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3 https://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7...
- mr-wendel 6y agoDo yourself a favor and read the linked section. The "elegant" method sure can be nice, but comes with a downside you really need to be aware of. I love shell scripting and this highlights one of the major problems with bash: small changes like this can appear completely interchangeable with other mechanisms for doing the same thing but introduce edge cases that can unexpectedly bite you. For example... consider what happens if "[ $foo -eq 0 ] && /bin/do-something" is the last statement within a function or the end of your script.
- e40 6y agoI came here to make this comment. It really needs to be a top-level comment and at the top. I have wasted many hours of my life tracking down buts where the idiom in the OP was used in a function. It leads to really hard to find bugs. Beware!!!
- catern 6y agoI cannot believe this is not at the top. Short-circuiting is useful and fun in places, but to suggest it as a general replacement for conditionals as the OP does is absolutely wrong and will cause bugs.
- jsrcout 6y agoDoes this caveat still apply when you only use a single short-circuit operator in a given command? As a long time shell scripter I'd honestly be a little afraid to use more than one at a time.