mtveezy
mtveezy

Reputation: 711

Why does $? -ne 0 work but $? != "0" not work?

I'm trying to do a simple check if the last expression was successful:

if [ $? -ne 0 ]; then
    chrome a.html
fi

and this form works. However, when I try to do:

if [ $? != "0" ]; then
    chrome a.html
fi

or without the "", it always executes. I'm not sure why this happens, as the following works:

if [ $(id -u) != "0" ]; then
#You are not the superuser
echo "You must be superuser to run this" >&2
exit 1
fi

I would think $? and $(id -u) both return an integer, and thus the comparison != "0" and -ne 0 should both work. However, it seems $? is not the same type as $(id -u). Any explanation?

Upvotes: 1

Views: 287

Answers (2)

Russ Thils
Russ Thils

Reputation: 150

I believe it is because $? returns output as an integer, but $(id -u) returns output as a string, instead of as an integer. The -ne operator is used for number comparison, whereas != is used with string comparisons. The comparison operator in the shell is not smart enough to automatically convert strings to an integer when you do the comparison using !=.

Upvotes: 0

John Hascall
John Hascall

Reputation: 9416

I do not see the behavior you describe:

#!/bin/bash
false
echo false returns $?
false
if [ $? -ne 0 ] ; then
        echo 'testing return -ne 0'
fi

false
echo false returns $?
false
if [ $? != "0" ] ; then
        echo 'testing return != "0"'
fi

true
echo true returns $?
true
if [ $? != "0" ] ; then
        echo 'testing return != "0"'
fi
echo done
exit 0

yields:

false returns 1
testing return -ne 0
false returns 1
testing return != "0"
true returns 0
done

Upvotes: 1

Related Questions