Дата создания файла в Linux
В свойствах файла в файловом менеджере Linux зачастую отображается только информация о дате последнего обращения к нему и дате изменения. Но вот дата создания там, к сожалению, отсутствует. А иногда нужно посмотреть именно ее, например, чтобы узнать, с какого момента ведется запись лога.
В данной статье мы расскажем о том, какие данные хранятся в файловых системах Linux и объясним, как узнать дату создания файла Linux . Будут упомянуты сразу же два удобных способа, каждый из которых со своими особенностями.
Дата создания файла Linux
В стандарте POSIX прописаны только 3 вида временных меток, которые должна хранить файловая система:
- atime – время последнего обращения к файлу.
- mtime – время последнего изменения содержимого.
- ctime – время последней модификации прав доступа или владельца.
По этой причине в старых файловых системах посмотреть информацию о дате создания файла зачастую невозможно. А вот в современных файловых системах (ext4, zfs, XFS и т. д.) она уже сохраняется.
Данные о дате создания записываются в специальном поле:
- Ext4 – crtime
- ZFS – crtime
- XFS – crtime
- Btrfs – otime
- JFS – di_otime
Есть два удобных способа просмотра этой информации: с помощью утилиты stat и debugfs. Но первый способ подойдет не для всех дистрибутивов Linux. Второй способ – универсальный, но не такой простой в использовании. Разберемся с каждым из них по отдельности.
1. С помощью stat
Утилита stat выводит подробные сведения о файле. В том числе выводится дата создания файла Linux. Для ее запуска в терминале достаточно указать путь к файлу. Для примера посмотрим информацию про изображение pic_1.jpeg, хранящееся в каталоге /home/root-user/Pictures:
Нужная информация записана в графе Создан. А с помощью опции -c получится задать определенные правила форматирования для вывода информации, например, оставив только нужную графу:
stat -c ‘%w’ /home/root-user/Pictures/pic_1.jpeg
отдельной статье. Можете с ней ознакомиться.
2. С помощью debugfs
В отличие от утилиты stat, описанной в предыдущем разделе, у debugfs нет таких ограничений по версии. А значит, она будет работать всегда. Но и процедура использования у нее несколько более запутанная. Связано это с тем, что для просмотра даты создания файла через debugfs, нужно узнать номер его inode и файловую систему. Получить inode выйдет с помощью команды ls с опцией -i, указав путь к файлу:
ls -i /home/root-user/scripts/main_script.txt
А для просмотра файловой системы пригодится команда df:
Теперь все нужные данные собраны, и можно переходить к использованию утилиты debugfs. Ей нужно передать опцию -R, указать номер inode, а затем название файловой системы:
sudo debugfs -R ‘stat <28>’ /dev/sda5
Подробное разъяснение о том, что такое inode, есть в специальной статье на нашем сайте.
Выводы
Мы разобрали два способа посмотреть дату создания файла Linux. Утилита stat несколько более удобная, ведь для нее достаточно указать только путь к нему. Но она не будет отображать нужную информацию до версии 8.31 GNU coreutils. А debugfs в этом плане более универсальная, но не такая простая в использовании. Ведь для получения данных она требует ввода номера inode файла и его файловую систему.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
How to find creation date of file?
I want to find out the creation date of particular file, not modification date or access date.
I have tried with ls -ltrh and stat filename .
8 Answers 8
stat -c ‘%w’ file on filesystems that store creation time.
The POSIX standard only defines three distinct timestamps to be stored for each file: the time of last data access, the time of last data modification, and the time the file status last changed.
Modern Linux filesystems, such as ext4, Btrfs, XFS (v5 and later) and JFS, do store the file creation time (aka birth time), but use different names for the field in question ( crtime in ext4/XFS, otime in Btrfs and JFS). Linux provides the statx(2) system call interface for retrieving the file birth time for filesystems that support it since kernel version 4.11. (So even when creation time support has been added to a filesystem, some deployed kernels have not immediately supported it, even after adding nominal support for that filesystem version, e.g., XFS v5.)
As Craig Sanders and Mohsen Pahlevanzadeh pointed out, stat does support the %w and %W format specifiers for displaying the file birth time (in human readable format and in seconds since Epoch respectively) prior to coreutils version 8.31. However, coreutils stat uses the statx() system call where available to retrieve the birth time only since version 8.31. Prior to coreutils version 8.31 stat accessed the birth time via the get_stat_birthtime() provided by gnulib (in lib/stat-time.h ), which gets the birth time from the st_birthtime and st_birthtimensec fields of the stat structure returned by the stat() system call. While for instance BSD systems (and in extension OS X) provide st_birthtime via stat , Linux does not. This is why stat -c ‘%w’ file outputs — (indicating an unknown creation time) on Linux prior to coreutils 8.31 even for filesystems which do store the creation time internally.
As Stephane Chazelas points out, some filesystems, such as ntfs-3g, expose the file creation times via extended file attributes.
How do I find the creation time of a file?
I need to find the creation time of a file, when I read some articles about this issue, all mentioned that there is no solution (like Site1, Site2).
When I tried the stat command, it states Birth: — .
So how can I find the creation time of a file?
6 Answers 6
There is a way to know the creation date of a directory , just follow these steps :
Know the inode of the directory by ls -i command (lets say for example its X)
Know on which partition your directory is saved by df -T /path command ( lets say its on /dev/sda1 )
Now use this command : sudo debugfs -R ‘stat <X>’ /dev/sda1
You will see in the output :
crtime is the creation date of your file .
What I tested :
- Created a directory at specific time .
- Accessed it .
Modified it by creating a file .
I tried the command and it gave an exact time .
@Nux found a great solution for this which you should all upvote. I decided to write a little function that can be used to run everything directly. Just add this to your
Now, you can run get_crtime to print the creation dates of as many files or directories as you like:
The inability of stat to show the creation time is due to limitation of the stat(2) system call, whose return struct doesn’t include a field for the creation time. Starting with Linux 4.11 (i.e., 17.10 and newer*), however, the new statx(2) system call is available, which does include a creation time in its return struct.
* And possibly on older LTS releases using the hardware enablement stack (HWE) kernels. Check uname -r to see if you are using a kernel at least at 4.11 to confirm.
Unfortunately, it’s not easy to call system calls directly in a C program. Typically glibc provides a wrapper that makes the job easy, but glibc only added a wrapper for statx(2) in August 2018 (version 2.28, available in 18.10). The stat command itself gained support for statx(2) only in GNU coreutils 8.31 (released in March 2019), however, even Ubuntu 20.04 only has coreutils 8.30.
But I don’t think this will be backported to LTS releases even if they do get, or are already on, newer kernels or glibcs. So, I don’t expect stat on any current LTS release (16.04, 18.04 or 20.04) to ever print the creation time without manual intervention.
On 18.10 and newer, you can directly use the statx function as described in man 2 statx (note that the 18.10 manpage is incorrect in stating that glibc hasn’t added the wrapper yet).
And in Ubuntu 20.10, you will be able to use stat directly:
For older systems, luckily, @whotwagner wrote a sample C program that shows how to use the statx(2) system call on x86 and x86-64 systems. Its output is the same format as stat ‘s default, without any formatting options, but it’s simple to modify it to print just the birth time.
You can compile the statx.c code, or, if you just want the birth time, create a birth.c in the cloned directory with the following code (which is a minimal version of statx.c printing just the creation timestamp including nanosecond precision):
In theory this should make the creation time more accessible:
- more filesystems should be supported than just the ext* ones ( debugfs is a tool for ext2/3/4 filesystems, and unusable on others)
- you don’t need root to use this (except for installing some required packages, like make and linux-libc-dev ).
Testing out an xfs system, for example:
However, this didn’t work for NTFS and exfat. I guess the FUSE filesystems for those didn’t include the creation time.
How to get file creation date/time in Bash/Debian?
I’m using Bash on Debian GNU/Linux 6.0. Is it possible to get the file creation date/time? Not the modification date/time. ls -lh a.txt and stat -c %y a.txt both only give the modification time.
13 Answers 13
Unfortunately your quest won’t be possible in general, as there are only 3 distinct time values stored for each of your files as defined by the POSIX standard (see Base Definitions section 4.8 File Times Update)
Each file has three distinct associated timestamps: the time of last data access, the time of last data modification, and the time the file status last changed. These values are returned in the file characteristics structure struct stat, as described in <sys/stat.h>.
EDIT: As mentioned in the comments below, depending on the filesystem used metadata may contain file creation date. Note however storage of information like that is non standard. Depending on it may lead to portability problems moving to another filesystem, in case the one actually used somehow stores it anyways.