Re: Bash true/false builtings undocumented? "false" not working?
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.
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.
On Fri, Aug 17, 2018 at 07:29:47PM +1000, Zenaan Harkness wrote:
> Is there a "cleaner" way to test the true/ error exit status other
> than using "$?", with bonus points for working in posix sh as well as
> Bash, ?
Simply use "if" like you're supposed to.
if mycommand arg1 arg2; then
echo "it worked"
else
echo "it failed"
fi
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"
Reply to: