0

What is the default behavior of for loop in terms of sorting when listing files in a directory?

e.g.

for sqlfile in *.sql; do mysql -u root -p pass < sqlfile; done

Is this documented somewhere?

pkaramol
  • 2,799
  • 6
  • 47
  • 79

2 Answers2

3

According to man bash's section on "Pathname Expansion":

If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern […]

This sorting depends on the value of $LC_COLLATE:

This variable determines the collation order used when sorting the results of pathname expansion […]

As you can see from the above, this has nothing to do with the for loop. Globs can be used in many ways, and their expansion is always sorted.

l0b0
  • 51,350
2

for loops don't sort, they give you the values in exactly the order they were presented:

$ for x in b a c ; do echo $x ; done
b
a
c

Globs, on the other hand, do sort alphabetically, regardless of if you use them in a for or anywhere else:

$ touch b a c
$ echo *
a b c
ilkkachu
  • 138,973