Sunny1985
Sunny1985

Reputation: 91

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?

Upvotes: 0

Views: 113

Answers (1)

chepner
chepner

Reputation: 530940

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.

Upvotes: 1

Related Questions