Search code examples
bashdash-shell

shell: Do wildcards guarantee alphabetical order?


When I have the files a.txt, b.txt and c.txt is it guaranteed that

cat *.txt > all_files.txt

or

cat ?.txt > all_files.txt

will combine the files in alphabetical order?

(In all my tests, the alphabetical order was preserved, but I'm not sure because for example with ls the order is undefined and need not be alphabetic - but it often is, because the files have often been written to the directory alphabetically)


Solution

  • No, it depends on the locale. The order is dictated by the collation sequence in the locale, which can be changed using the LC_COLLATE or LC_ALL environment variables. Note that bash behaves differently in this respect to some other shells (e.g. Korn shell).

    If you have a locale setting of C or POSIX then it will be in character set order. Otherwise you will probably only notice a difference with mixed case letters, e.g. the sequence for en_ locales is aAbBcC ... xXyYzZ. For example see http://collation-charts.org/fc6/fc6.en_GB.iso885915.html.

    Available locales may be listed using locale -a.

    Edit: another variable LANG is available, but it is generally not used much nowadays. According to the Single UNIX Specification it is used: in the absence of the LC_ALL and other LC_* ... environment variables.