find command default sorting order

Solution 1:

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.

Solution 2:

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


Solution 3:

I have been working in UNIX/Linux since 1984/1991 respectively and the first command I was taught was find. Linux/GNU has put pretty much everything you need into the current find command so play around with it.

Here are some helpful tips for sorting find output. The -printf option gives you lots of options to enable more complex sorting and file info presentation. It is the best for problems like this. Play with it to see what will work for you. Using -printf you can customize and delimit the results the way you want. This helps quite a bit when you need to post process the results. I hope this helps someone.

  1. If you use -ls and want to sort by file name the 11th field is the file name so you can do the following. The sort -k option can take multiple fields to sort on as well.

    find /path -ls | sort -k11

  2. If you want finer grain control i.e.sort by date/time in ascending or descending order use the -printf "" option. See the manual for more detail, but the following is an example that will print with fractional seconds so it is very accurate.

EXAMPLE DATE/TIME: 2016-09-17+12:09:57.9013929800

find /path -printf "%T+ %p\n" | sort -n # Ascending

find /path -printf "%T+ %p\n" | sort -nr # Descending

Another way to do this without characters in the date/time string is.

EXAMPLE DATE/TIME: 20160917120013.8101685040

find /path -printf "%AY%Am%Ad%AH%AM%AS %p\n" | sort -n

Tags:

Linux

Shell

Find