I'm building a script that tries to run some commands on a server (over SSH), and writes on the screen whether they were successful.
I noticed a strange behaviour for $?
, namely not being 0
when the previous command failed.
Initially, I had:
ssh <user>@<server> <<EOF
false
if [ $? -ne 0 ]; then
echo "It failed"
else
echo "It worked"
fi
EOF
If I copy and paste the script inside <<EOF
and EOF
, it prints It failed
. If I run it with the ssh
part, it prints It worked
. To simplify, I then tried:
ssh <user>@<server> <<EOF
false
echo $?
EOF
Same thing happened. If I copy-paste or type the commands inside, it prints 1
, but if I run all of it (including the ssh
), it prints 0
.
The same error happens if I directly use bash this way
bash <<EOF
false
echo $?
EOF
or
bash -c "false; echo $?"
Why does this happen? How can I check if the previous command failed in this context?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…