Why bash -c "false, echo $?" print 0?
I am creating a script that tries to run some commands on the server (via SSH) and records on the screen if they were successful.
I noticed strange behavior for $?
, namely 0
when the previous command failed.
I originally 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 a part ssh
, it prints It worked
. To simplify, I then tried:
ssh <user>@<server> <<EOF
false
echo $?
EOF
The same thing happened. If I copy-paste or type commands inside it prints 1
, but if I run all of it (including ssh
) it prints 0
.
The same error occurs if I directly use bash this way
bash <<EOF
false
echo $?
EOF
or
bash -c "false; echo $?"
Why is this happening? How can I check if the previous command did not work in this context?
source to share
This is due to the change in the variable. As you write bash -c "false; echo $?"
, the variable is expanded before the commands are run. This way, your team matches exactly bash -c "false; echo 0;"
if your previous team was successful.
Try it to get the correct result bash -c 'false; echo $?'
. This prevents the variable from expanding, it will be expanded upon interpretation.
For this version of the document, follow these steps:
bash << 'EOF'
false
echo $?
'EOF'
In this case, you need to specify a document separator. But be careful that the syntax you have to use is the syntax for the shell you use to enter the command. In the example I was in tcsh
and it requires using the same open and close constraint. In a section, the bash
closing separator must be the first after the quote is removed.
source to share