191

In what order are the dated ordered by? Certainly not alphanumeric order.

ls -lt sorts by modification time. But I need creation time.

InquilineKea
  • 6,262

7 Answers7

148

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.

Stephen Kitt
  • 434,908
  • 1
    In Cygwin it is ls -c.

    ls --help shows what -c does when combined with -l and -lt.

    – Aaron D. Marasco Sep 12 '11 at 01:37
  • 8
    @Aaron No, the ctime is not the creation time. It's a common confusion based purely on the fact that “ctime” and “creation” start with the same letter, but there is no relation between ctime and creation time. I've updated my answer to address this confusion. – Gilles 'SO- stop being evil' Sep 12 '11 at 11:31
  • LOL my bad. I was trying to confirm the Cygwin part for ya (IIRC your original post had a possible command). It does specifically say "ctime (time of last modification of file status information)" if I had paid attention. – Aaron D. Marasco Sep 13 '11 at 02:02
  • 1
    Adding to @Gilles answer; I use an NFS 3.x file server (unsure on the underlying file system; it's either UFS or ZFS, though I'm guessing UFS). Under Redhat 6.x: -U sorts by creation time. Under Solaris 10.x: /usr/bin/ls does not support -U, /usr/ucb/ls supports -U and does sort by creation time. These results obviously depend on the filesystem storing that info in the first place. – Brian Vandenberg Jun 12 '12 at 19:44
  • 1
    @brian-vandenberg, under RHEL7 ls -U is do not sort; list entries in directory order (I assume RHEL6 was identical). That's not file creation time. – Franklin Piat Mar 27 '15 at 21:14
  • 1
    @FranklinPiat, picking a nit here, but that could be creation order, if no files were ever unlinked from that directory. Incidentally, in FreeBSD, (and by extension OSX), ls -f will list directory contents unsorted. – ghoti Feb 12 '16 at 11:30
  • 1
    @ghoti If no files were ever deleted (or moved/renamed/hardlinked/…) in the directory, then the directory order is creation order on some filesystems, but not all. That's not true on ext4, for example. I don't know if it's true on Solaris's UFS. – Gilles 'SO- stop being evil' Feb 12 '16 at 12:34
  • 2
    https://www.freebsd.org/cgi/man.cgi?query=ls&sektion=1&manpath=FreeBSD+6.2-RELEASE – FreeBSD 6.2-RELEASE was announced 2007-01-15 (notes) with ls(1) option -U to use time when file was created for sorting or printing. For ls(1) in 11.0-RELEASE the page notes that this option is not defined in IEEE Std 1003.1-2001 (``POSIX.1''). – Graham Perrin Mar 26 '17 at 00:47
46

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 or XFS), do save this information within the file metadatas. There is just no standard way to get it, but there is a way:

Note: this answer mainly covers Linux systems.

UPDATE 2021: the new ls command option

According to Stéphane Chazelas, the ls version from coreutils 8.32 (and glibc 2.28, and kernel 4.11) is now capable of using the new statx(2) system call (see end of this answer) to extract the creation time metadata.

So to list files sorted by creation/birth date/time, you can use:

ls -lt --time=birth

The -t option will sort by the type of time indicated with the --time option (I suspect birth can be changed by creation if preferred).

Add -r to reverse the sort order.

debugfs for extN filesystems

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.

Use a VCS?

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 version control system. But you may try to have a look at the ext4 API...

The stat command (2021 updated)

I tried the stat -c '%w' myfile command on a ext4 filesytem on a (recent enough) Ubuntu system without success (it just answers -).

UPDATE 2021: according to Thomas Nyman, the above command works on Linux if you have at least coreutils 8.31, glibc 2.28 & kernel 4.11. That does not sort files by itself though you could try:

stat -c '%w %n' * | sort -n 

to achieve that. Use %W if you don't care about human readable date. Add -r option to sort to reverse order.


UPDATE 2020: 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.

Totor
  • 20,040
9

On Linux systems running kernel 4.11 or later, with glibc 2.28 or later, and coreutils 8.31 or later, stat can show a file’s birth time on file systems which store it. Output similar to that of ls -l can be obtained with

stat -c "%A %4h %U %G %10s %.16w %n" -- *

and sorted output (assuming no filename with newline characters) with

stat -c "%.10W %A %4h %U %G %10s %.16w %n" -- * |
  sort -k1,1n |
  cut -d' ' -f2-

With coreutils 8.32 or later, ls can display and sort using the birth time, using the --time=birth option:

ls -l --time=birth

The stat invocations above use these formatting options:

  • %.10W: the birth time, in seconds since the Unix epoch (with a 10 digit fractional part).
  • %A: the file type and permissions, in ls -l format
  • %4h: the number of hard links to the file, aligned to four characters
  • %U: the owning user’s name
  • %G: the owning group’s name
  • %10s: the file size, aligned to ten characters
  • %.16w: the birth time, in human-readable format, truncated to sixteen characters (enough to show the year, month, day, hour, minute and second)
  • %n: the file’s name
Stephen Kitt
  • 434,908
6

[Edit]
Use this command ls -lct to sort files as per ctime (time of last modification of file status information).

4

Here's a Perl script which uses Totor's answer to achieve what you want (if your filesystem is ext4).

Works on my home machine (Ubuntu) and my server (CentOS), but not tested beyond that, so ymmv.

#!/usr/bin/env perl

use Modern::Perl '2009';

use DateTime;


# Open the current directory for reading
opendir my $dh, "." or die "Unable to open directory: $!";

# Create a hash to save results into
my %results;
my %datestamp;

# Loop through the directory getting creation date stats for each file
while ( my $filename = readdir $dh ) {
    # Skip non-files
    next if $filename eq '.' or $filename eq '..';

    # Save the ls output for this file/directory
    $results{ $filename } = `ls -ld $filename`;

    my $stats = `debugfs -R 'stat $filename' /dev/sda6 2>/dev/null`;
    # crtime: 0x51cd731c:926999ec -- Fri Jun 28 12:27:24 2013
    $stats =~ m/crtime\: \w+\:\w+ -- (.+?)\n/s;
    my $datestring = $1;

    # Dissect date with a regexp, ick
    my %months = (
        'Jan' => '1',
        'Feb' => '2',
        'Mar' => '3',
        'Apr' => '4',
        'May' => '5',
        'Jun' => '6',
        'Jul' => '7',
        'Aug' => '8',
        'Sep' => '9',
        'Oct' => '10',
        'Nov' => '11',
        'Dec' => '12',
    );
    $datestring =~ m/\w+ (\w+)  ?(\d+) (\d\d)\:(\d\d)\:(\d\d) (\d\d\d\d)/;

    # Convert date into a more useful format
    my $dt = DateTime->new(
        year   => $6,
        month  => $months{$1},
        day    => $2,
        hour   => $3,
        minute => $4,
        second => $5,
    );

    # Save the datestamp for this result
    $datestamp{ $filename } = $dt->iso8601;
}

# Output in date order
my @filenames = sort { $datestamp{$a} gt $datestamp{$b} } keys %datestamp;

foreach my $filename ( @filenames ) {
    print $results{ $filename };
}
Denny
  • 41
  • 1
    Also good to mention that some files may have metadata (such as exif) which record the creation date/time. If all of your files happen to be digital photos for example, you most likely have this data. Here is an example using perl's Image::ExifTool. – Jonathan Cross Jan 24 '17 at 20:48
  • Lots of warnings/errors in this.. Use of uninitialized value $datestring in pattern match (m//) at sort-by-create-time.pl line 43. Use of uninitialized value $1 in hash element at sort-by-create-time.pl line 48. Use of uninitialized value in subroutine entry at /usr/lib/x86_64-linux-gnu/perl5/5.22/DateTime.pm line 197. Use of uninitialized value within @DB::args in list assignment at /usr/share/perl/5.22/Carp.pm line 228. The 'minute' parameter (undef) to DateTime::new was an 'undef'... – user239558 Mar 06 '20 at 21:01
1

To do it in shell. ls do not provide creation time but change time. Only debugfs can show creation time if partition is ext4

disk=$(df -Th . | grep ext4  |awk '{print $1}')
for file in "."/*
do
    inode=$(ls -i $file | awk '{print $1}')
    crtime=$(debugfs -R "stat <$inode>" $disk 2>/dev/null | grep crtime |  awk -F'-- ' '{print $2}' | awk '{print $2,$3,$5,$4}')

    printf "$crtime\t$file\n"
done | sort -k4 | sort -n -k 3 -k 1M -k2 -k4
0

In case you want to find it in GUI, not in CLI:
In Ubuntu 21.04, I can install KDE Dolphin File Manager, and see " Created" column in that file manager interface.

enter image description here

muru
  • 72,889
qamnott
  • 101
  • 1
    "As of July 2021, On Ubuntu", what does that mean? Does it work on Ubuntu 18.04 as well? – muru Jul 30 '21 at 11:38
  • 2
    This still presumes that the file "birth"/"creation" time is even available on he underlying file system, which it may not be. Most modern Un*x file systems and tools are capable of tracking creation time, but many still use the long established tradition of only tracking "(a)ccess", "(m)odification", and "inode (c)hange" times. – C. M. Jul 30 '21 at 15:27
  • @muru, I am using Ubuntu 21.04. I haven't tested with Ubuntu 18.04. The "As of July 2021" was mentioned there because this question was asked 9 years and 10 months ago; and things may change later on. Therefore, I thought it'd be useful to specify the date. – qamnott Aug 02 '21 at 09:04
  • @C.M., I think I am well aware of that technical depth. Just to share from a simple level of end user experience with commonly used programs. – qamnott Aug 02 '21 at 09:06
  • @qamnott that "as of" is then completely useless and misleading, since it doesn't provide the version info, and we can see when this answer was posted right beneath it. – muru Aug 02 '21 at 11:02
  • @gamnott: You may be well aware of technical insight, but not everyone who comes across this answer will be as knowledgeable. My comment was directed at your answer, not at you, as the "ctime" field from the stat() family of system calls is one of the more commonly misunderstood fields. Especially among those coming from a DOS/WIN programming background and learning a Un*x system. – C. M. Aug 03 '21 at 14:35
  • Understood. Thanks for your explanation, @muru. – qamnott Aug 06 '21 at 10:24
  • Dear @C.M., I have to sincerely apologise for my typing mistake and thereby rendering an unintended meaning of response. And I do accept and admire your detailed and helpful explanation. What I meant was that "I am not well aware of...". I am at a beginner level with Linux. Happy learning more. (*I read these two new comments three times before adding.) – qamnott Aug 06 '21 at 10:32
  • @C.M., please explain further. What does that date-time values refer to in that "Created" column as seen in KDE Dolphin file manager app that I am having on my Ubuntu 21.04 machine? – qamnott Aug 06 '21 at 10:35
  • @muru, I updated my original answer to provide version info. – qamnott Aug 06 '21 at 10:43
  • 1
    @qamnott: Not everyone who comes here seeking answers (or helping with answers) will have a "current" OS installed. Some may have older versions, and not all of them keep a record of file creation times. You will end up confusing some when you assume everyone else has the same screen, with the same information, as you do. Take a look at this question, for example. – C. M. Aug 07 '21 at 11:25