Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

what is the default sorting order for entries returned by the linux find command?

For example, if I issue

find . -type f -name '*mp3' 

and the output consists of multiple files across multiple sub-folders, what is the default order in which directories are listed? At the same time, what is the sorting order in which files within an individual directory are listed?

Sometimes it returns:

./B/01.mp3
./A/01.mp3
./A/04.mp3
./A/02.mp3

See how first the contents of directory B is listed, then that of directory A. At the same time within directory A, files are listed in a funny order.

share|improve this question
    
From experience it seems to be consistent per install, ie. if you have the same set of files on two machines it will always return one order on one machine, and a completely different one on the other. I have wondered why before, +1 –  James Lawrie Sep 16 '10 at 13:34
    
I have an FM transmitter in my car and it always plays songs from my flash card in strange order. I never figured it, but I recognized it was exactly the same order in which the above command returned its output –  Nasko Sep 16 '10 at 14:10
add comment

2 Answers

up vote 3 down vote accepted

find will be traversing the directory tree in the order items are stored within the directory entries. This will (mostly) be consistent from run to run, on the same machine and will essentially be "file/directory creation order" if there have been no deletes.

However, some file systems will re-order directory entries as part of compaction operations or when the size of the entry needs to be expanded, so there's always a small chance the "raw" order will change over time. If you want a consistent order, feed the output through an extra sorting stage.

share|improve this answer
    
Thanks for your detailed answer! So, if my FM transmitter (see my prev. comment) plays tracks in the order the find command would list them, I'm not able to control in what order I'd like them to be played. –  Nasko Sep 17 '10 at 8:33
    
Well, the flash card probably uses a FAT file system and if I remember correctly, manipulating the order of FAT entries is pretty easy with a file system debugger. It may, possibly, be worth copying the songs from the current flash onto a new flash, in the order you want them played, that may be easier. –  Vatine Sep 17 '10 at 10:39
add comment

You shouldn't rely on a particular output order from find and instead should use sort and other means to specifically control the order.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.