Sunny1985 Sunny1985 - 1 year ago 36
Bash Question

Why is the IF condition is being ignored - Shell

I have an

statement like below.

if [ $? -eq 0 ]
echo "err A is $?"
echo "DO THIS"
echo "Do THAT"

But when I execute this it returns:

'[' 1 -eq 0 ']'
echo 'err A is 1'
err A is 1

As per the statement, it should return the alert 'NOK'. Why does this behaviour occur?

Answer Source

Your echo, being the last command of the condition, is what if tests to determine which branch to take. Try this instead:

if rv=$?; echo "err A is $rv"; [ "$rv" -eq 0 ]; then

Note that in your original, the value of $? in your echo command is the result of the [ that immediately precedes it, not the value that [ tests.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download