[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: unexpected behavior
From: |
Greg Wooledge |
Subject: |
Re: unexpected behavior |
Date: |
Thu, 12 Jan 2023 13:50:14 -0500 |
> On Thu, Jan 12, 2023 at 06:24:11PM +0100, Christof Warlich wrote:
> > can anyone explain why the following line prints 0 instead of 1?:
> >
> > $ stat=0; false || echo hi && echo ho && stat=1 | tee /dev/null; echo $stat
Oh, here's another tangent that I didn't follow in my original
message.
It's unwise to mix && and || in a single command. Some people believe
that the following two script fragments are equivalent:
if test "$foo"; then
cmd1
else
cmd2
fi
and
test "$foo" && cmd1 || cmd2
These two fragments are *not* equivalent. You can't use && || as a
substitute for if/then/else.
In the first one, the test command will be executed, and then exactly
one more command will be executed -- either cmd1, or cmd2, but never
both.
In the second fragment, the test command will be executed, and then
cmd1 might be executed, or cmd2 might be executed, OR BOTH. This is
because the exit status of test "$foo" && cmd1 is used to decide whether
to follow the || branch. If test "succeeds" (exits 0) but cmd1 "fails"
(exits nonzero), cmd2 will also be executed.
unicorn:~$ test "string" && false || echo "uh oh"
uh oh
This is usually not what you want.
See also <https://mywiki.wooledge.org/BashPitfalls#pf22>.