-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, Aug 17, 2018 at 08:23:51AM -0400, Greg Wooledge wrote: > On Fri, Aug 17, 2018 at 06:46:54PM +1000, Zenaan Harkness wrote: > > $ test $? && echo ok || echo error $? > > Others have already pointed out that test $? is not what you think it > is. When the test command is given 1 argument, it tests that argument's > string length. If the string length is 0, then it's false. If the > string length is non-zero, then it's true. > > The string length of $? is always non-zero, so test $? is always true.
Exactly. > But what I really wanted to point out is that the x && y || z construct > is BROKEN and WRONG. See <https://mywiki.wooledge.org/BashPitfalls#pf22> > for the verbose explanation. All generalizations suck :) [...] > Or, if you only care about one of the two cases, you may use EITHER > the && or the || operator. Just never, ever use both of them in the > same compound command. > > mycommand arg1 arg2 || die "whoopsie" The construction foo && echo "bar" || echo "baz" does probably work, because echo's exit status is (always?) 0 (the bash builtin's documentation mumbles something about "write error"). And then, the order matters -- first && then ||. I think such idiomatic constructions are OK as long as you know what you're doing. As soon as the branches contain more complex stuff, I agree you shouldn't do it: even if you've convinced yourself that it works, the code becomes obscure and difficult to understand/change by someone else (which might be yourself two years down). Cheers - -- tomás -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.12 (GNU/Linux) iEYEARECAAYFAlt20R4ACgkQBcgs9XrR2kY8CgCfYfHXfeDyqQ/ebWZrs24BPHIE 7NUAniyfZd2F/A/f27P1YVuuFP4nYnGi =hE0n -----END PGP SIGNATURE-----