We wish to sort a set of arbitrary files by the order in which they were created. We cannot however rely on the system clock (hence the 'created at' time), file name, or time since reboot (e.g. millis
).
We do however have a linux operating system and file system. We should therefore be able to use the inode
ids of the file to order them.
Create some files, resetting the system clock in between each creation. The files will start with a number that is deliberately out of sequence in order to show that we're not sorting just by name.
$date
ke 12.10.2022 13.43.56 +0300
$ touch 9-first-file.txt
System Clock Changed
$date
su 10.1.2021 13.44.02 +0200
$ touch a-second-file.txt
System Clock Changed
$date
ma 10.1.2022 13.45.04 +0200
$ touch 0-third-file.txt
System Clock Reset to Present Time
$ ls -lh
total 0
-rw-rw-r-- 1 abarber abarber 0 tammi 10 2022 0-third-file.txt
-rw-rw-r-- 1 abarber abarber 0 loka 12 13:44 9-first-file.txt
-rw-rw-r-- 1 abarber abarber 0 tammi 10 2021 a-second-file.txt
We wish to order these by ascending order of creation. If we were to use the Unix 'creation time' order we would see, incorrectly:
$ ls -lr
total 0
-rw-rw-r-- 1 abarber abarber 0 tammi 10 2021 a-second-file.txt
-rw-rw-r-- 1 abarber abarber 0 loka 12 13:44 9-first-file.txt
-rw-rw-r-- 1 abarber abarber 0 tammi 10 2022 0-third-file.txt
We can see the inode id
number with the following (but not sort by it):
$ ls -li
total 0
13246221 -rw-rw-r-- 1 abarber abarber 0 tammi 10 2022 0-third-file.txt
13241694 -rw-rw-r-- 1 abarber abarber 0 loka 12 13:44 9-first-file.txt
13241734 -rw-rw-r-- 1 abarber abarber 0 tammi 10 2021 a-second-file.txt
Note that these numbers ascend with file creation order. The following Python script would print these files out in creation order, regardless of creation time and file name:
import glob
import os
files = glob.glob("./*.txt")
files.sort(key = lambda f: os.stat(f).st_ino)
print(files)
Output:
['./9-first-file.txt', './a-second-file.txt', './0-third-file.txt']