Herbert
Herbert

Reputation: 57

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)?

Upvotes: 3

Views: 44

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

[[ 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=

Upvotes: 5

Related Questions