简体   繁体   中英

Why does “[[ '>' > '0' ]]” return false while “[ '>' \> '0' ]” returns true?

String comparison is ASCII comparison, so

[ '>' \> '0' ]

should have same result as

[[ '>' > '0' ]]

But why does the first return true(0) while the second returns false(1)?

[[ uses the current locale for string comparisons, [ does not.

If you set LC_ALL to C , the [[ variant will also return true:

pax$ LC_ALL=;  if [[ ">" > "0" ]] ; then echo yes; fi
pax$ LC_ALL=C; if [[ ">" > "0" ]] ; then echo yes; fi
yes

My default locale, en_US.UTF-8 , has > sorting before 0 , as per the chart here . Switching the local to C (collation based on raw byte values rather than culture-specific ordering), changes the behaviour.

If you're on Linux (this may also work on other UNIX brethren), the locale command should tell you what your current settings are, if you want to investigate/confirm:

pax$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_ALL=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM