Sunny1985 Sunny1985 - 3 months ago 13
Bash Question

Why is the IF condition is being ignored - Shell

I have an

if
statement like below.

if [ $? -eq 0 ]
echo "err A is $?"
then
alrtid="OK"
echo "DO THIS"
else
echo "Do THAT"
alrtid="NOK"


But when I execute this it returns:

'[' 1 -eq 0 ']'
echo 'err A is 1'
err A is 1
alrtid=OK


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.