[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: not sure about number comparison
From: |
David |
Subject: |
Re: not sure about number comparison |
Date: |
Mon, 20 Feb 2023 00:18:43 +1100 |
On Sun, 19 Feb 2023 at 20:29, winnie hw <hitwinds@gmail.com> wrote:
> I am a bit confused about the following 4 statements.
>
> $ if [ $(id -u) -ne 0 ];then echo true;fi
> true
>
> $ if [ $(id -u) != 0 ];then echo true;fi
> true
Hi,
-ne operator compares the integer value, whereas
!= operator compares the characters in the string.
These are not the same thing!
When the strings are both integers, these comparison
methods will give the same result in many cases.
However, not always. Example of different strings that
have the same integer value:
$ a=1 ; b=+1
$ [[ $a == $b ]] ; echo $?
1
$ [[ $a -eq $b ]] ; echo $?
0
Note: $? shows the exit status of the test.
0=true and 1=false. See here:
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Exit_Status
More info about comparison with test, [ and [[:
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Blocks_.28if.2C_test_and_.5B.5B.29
The answer to your second question:
http://mywiki.wooledge.org/BashFAQ/031