How do I do a ls and then sort the results by date created?
Most unices do not have a concept of file creation time. You can't make ls
print it because the information is not recorded. If you need creation time, use a version control system: define creation time as the check-in time.
If your unix variant has a creation time, look at its documentation. For example, on Mac OS X (the only example I know of), use ls -tU
. Windows also stores a creation time, but it's not always exposed to ports of unix utilities, for example Cygwin ls
doesn't have an option to show it. The stat
utility can show the creation time, called “birth time” in GNU utilities, so under Cygwin you can show files sorted by birth time with stat -c '%W %n' * | sort -k1n
.
Note that the ctime (ls -lc
) is not the file creation time, it's the inode change time. The inode change time is updated whenever anything about the file changes (contents or metadata) except that the ctime isn't updated when the file is merely read (even if the atime is updated). In particular, the ctime is always more recent than the mtime (file content modification time) unless the mtime has been explicitly set to a date in the future.
Unfortunately, the stat(2)
API does not provide a way to get the file creation time, as it is not required by the Unix standards.
However, some filesystems, as ext4
, do save this information within the file metadatas. There is just no standard way to get it, but there is a way (ext
filesystems only):
debugfs -R 'stat partition/relative/path/to/file' /dev/sda1
You would get something like that mentioning crtime
(not ctime
!) if you use ext4
.
ctime: 0x513a50e5:d4e448f0 -- Fri Mar 8 21:58:13 2013
atime: 0x513dd8f1:04df0b20 -- Mon Mar 11 14:15:29 2013
mtime: 0x513a50e5:d4e448f0 -- Fri Mar 8 21:58:13 2013
crtime: 0x513a259a:35191a3c -- Fri Mar 8 18:53:30 2013
This command may take some time to return, probably because it also lists every extent related to the file.
Now if you want to order files by creation date, I guess this is not easily (nor properly) possible. As Gilles says, it would probably be easier if you'd use a revision control system. But you may try to have a look at the ext4
API...
I tried the stat -c '%w' myfile
command on a ext4
filesytem on a (recent enough) Ubuntu system without success (it just answers -
).
UPDATE : since Linux kernel 4.11, a new statx(2)
system call has been introduced. Its API can give access to file creation time, if the info is available on the filesystem. To my knowledge, there is no standard/stable userspace utility allowing us to get this info yet, but it will probably appear in some time. This is not a standard POSIX interface though, but a Linux specific, says the man
:
statx() was added to Linux in kernel 4.11; library support was added in glibc 2.28.
statx() is Linux-specific.
[Edit]
Use this command ls -lct
to sort files as per ctime
(time of last modification of file status information).