Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range in bash file-pattern and case-sensitivity

Tags:

bash

shell

I encountered the following IMHO strange behavior in bash's file-patterns:

$ ls
Basic1  datei1  datie2  sdfl
$ ls [a-z]*
Basic1  datei1  datie2  sdfl
$ ls [abcdefghijklmnopqrstuvwxyz]*
datei1  datie2  sdfl

Why is the pattern with the range [a-z] not case-sensitive? Bug or feature?

Note:

  1. The bash-Option nocaseglob is off (otherwise, the second pattern given above should have also been case-insensitive...):

    $ shopt nocaseglob
    nocaseglob  off
    
  2. My bash-version:

    $ bash --version
    GNU bash, Version 4.2.24(1)-release (i686-pc-linux-gnu)
    

GNU bash, Version 4.2.24(1)-release (i686-pc-linux-gnu)

like image 626
phynfo Avatar asked Apr 21 '26 17:04

phynfo


1 Answers

If you only want file names that start with a lower-case, use

ls [[:lower:]]*

Edit

Answering F. Hauri's comment: section 3.5.8.1 of the reference manual says it all. But before we read it, let's play a little bit (YMMV): create a new scratch directory and

$ # Create lots of cool files
$ touch {a..z} {A..Z}
$ ls
a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z
A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
$ ls [a-b]
a A b
$ # Do you get it?
$ ls [a-B]
a A b B

So it seems that bash's alphabetical order (here, on my machine, with my settings) is:

aAbBcCdDeE...

This might explain why you got your results (it seems your settings are similar to mine).

Now, go and read the section 3.5.8.1 of the reference manual and you'll understand that things are not as simple, that the ordering depends on the value of the environment variable LC_COLLATE.

So try:

$ LC_COLLATE=C
$ ls [a-b]
a b

Yeah!

Moral

If you want lower cases, don't use [a-z] as this will highly depend on the local settings. Instead, use [[:lower:]]. In the reference manual, you'll also find several other useful character classes.

Bottom Line

So, bug or feature? You now have the answer ;-)

Hope this helps!

like image 166
gniourf_gniourf Avatar answered Apr 23 '26 22:04

gniourf_gniourf