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?
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?
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.
for
does not sort ever. It is the glob (*.sql
) that is doing the sorting.
– ctrl-alt-delor
May 30 '18 at 09:42
for
loop works.
– l0b0
May 30 '18 at 09:43
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
*.sql
) that is doing the sorting. – ctrl-alt-delor May 30 '18 at 09:41