3

I wanted to know if iterating over files in directory with

for f in directory/*

will have some default order of processing entries (file name, created date, etc.?), or is it non-deterministic?

It is probably obvious, but I couldn't find the information.

0

2 Answers 2

1

The order will be in lexicographic order (alphabetical order). It will be exactly the same as what you see if you type ls directory/* at a Bash shell prompt.

If you want to sort by modification time, you can use ls -t. See man ls for other sorting options.

1

directory/* is expanded by the shell first (normally bash). Running echo directory/* will echo all matching files, and bash will sort these matching elements lexicographically first, before passing them as arguments to echo, which then prints them.

In the case of running ls directory/*, the directory/* is first expanded by the shell, and then presented as a list of arguments to ls. The ordering which ls then uses to output the files depends on the optional arguments supplied to it, which allow for outputting the file list based on alternative criteria, such as size, time modified etc, but this sorting is done internally within the ls binary itself, after it has been passed the lexicographically sorted expanded argument list from the bash shell.

Not the answer you're looking for? Browse other questions tagged .