[Solved] FOR loop / IF statement returning error

The code at the bottom is a simplified example of what we have.

If I use the following:

 [ $? != 0 ] && echo "echo failed"

$? returns 1

When I use

if [ $? != 0 ] ; then  echo "echo failed" ; fi

$? returns 0

Does anyone know what's wrong with this?

Using AIX 6.1 and KSH

for NUM in 1 2 3
do
    echo $NUM
    for LET in A B C
    do
        echo $LET
        [ $? != 0 ] && echo "echo failed"
        echo $?
    done
done

Thankyou.

You're using a string comparison operator [ $? != 0 ] .

Try -ne instead of !=

Thanks for the quick response.

Using -ne also doesn't work

Because you cant use $? like that...

        let DID=$?
        echo DID: $DID
        #let DID=1
        [ $DID != 0 ] && echo "echo failed"
        echo DID: $DID

I set DID to 1 so to see your condition work... in other words your script will run with DID=0 always since the command producing the result of it ($?) at that point is successful...
I know Im not very clear but its friday...

So your script now :

for NUM in 1 2 3
do
    echo $NUM
    for LET in A B C
    do
        echo $LET
        let DID=$?
        echo DID: $DID
        [ $DID != 0 ] && echo "echo failed"
        echo $?
    done
done

There is nothing wrong. What you are seeing is correct behavior. In each case you are seeing the exit status of the last command to run.

In the first case, the last command before echoing $? is [ $? != 0 ] . The test failed and so $? is set to 1.

In the second case, you're seeing the exit status of the if-statement itself. Since the conditional test fails, the if-statement does not execute further, the list of commands after then does not execute. So the if-statement itself sets $? to 0.

That following quote is from POSIX: Shell Command Language, but your KSH man page should contain similar text.

Regards,
Alister

1 Like

Alister,

Thanks for the explanation - makes perfect sense.