You seem to only run the if statement if nc completes successfully:
nc ... && if ...
This explains why 0 is never outputted. Since the if statement is not executed when nc fails, the else branch of the if statement is always unreachable.
Instead, use nc directly with if:
if nc -z 10.102.10.22 10003 >/dev/null; then
echo 1
else
echo 0
fi
You could probably also write this particular statement using short-circuit logic:
nc -z 10.102.10.22 10003 >/dev/null && echo 1 || echo 0
... but it's technically not the same thing as the if statement. This last command would execute echo 0 if either of nc or echo 1 failed.
To get the nc command to exit after 10 seconds, use the GNU utility timeout:
if timeout 10 nc -z 10.102.10.22 10003 >/dev/null; then
echo 1
else
echo 0
fi
The special variable $? is very rarely used. You only need it in situations where you need to use the exit status of some command later than one or more further commands have executed. For example, when returning an exit status from a shell function in some cases:
myfunction () {
grep -q 'pattern' file
err=$?
if [ "$err" -ne 0 ]; then
echo failed >&2
fi
return "$err"
}
Here, both the [ ... ] test and the echo resets $?.