mtime, ctime, and birth time in Linux: what stat shows
One timestamp changes with chmod, another with writing, and birth time may be unknown. We verify this on an isolated file and demonstrate what conclusions cannot be drawn from stat alone.

In this article
Короткий ответ: в GNU stat поле mtime показывает время последнего изменения данных файла, ctime — время последнего изменения состояния inode, а birth — время рождения файла, если файловая система его предоставляет. ctime не означает время создания. Одна отметка задаёт границу для расследования, но сама по себе не называет пользователя, процесс или причину изменения.
Для читаемого снимка нужны отдельные директивы: %y для mtime, %z для ctime и %w для birth time. Если время рождения неизвестно, %w выводит -. Сохраняйте часовой пояс и дробную часть секунды: без них два снимка труднее сопоставить.
Снимаем поля отдельно
Сначала проверим версию утилиты и точный путь. Отдельно установите, является ли путь символьной ссылкой: без --dereference GNU stat читает метаданные самой ссылки, а с --dereference — её цели. Команда ниже без этого параметра только читает метаданные указанного объекта. Подставьте существующий файл; не меняйте его времена ради эксперимента на рабочем сервере.
stat --version
stat --printf='name=%n\nmode=%A\nsize=%s\nmtime=%y\nctime=%z\nbirth=%w\n' -- /path/to/file
В выводе важны не только значения времени. Поля mode и size помогают понять, что именно изменилось, а полный путь защищает от сравнения двух одноимённых файлов. Для расследования большого дерева полезно дополнительно сохранить device и inode, но это уже отдельные поля и отдельный вопрос.
Поле | Что фиксирует | Чего не доказывает |
|---|---|---|
| Последнее изменение данных файла | Какой пользователь или процесс записал данные и что именно изменилось |
| Последнее изменение состояния | Время создания файла |
| Время рождения файла, если его хранит и отдаёт файловая система | Что файл не копировали и не восстанавливали |
| Последний учтённый доступ к данным | Каждое чтение: обновление может быть отложено или отключено |
Семантика директив описана в руководстве GNU stat. Когда обновляются сами времена и какие есть ограничения, поясняет раздел GNU File timestamps; определения Linux также приведены в inode(7). Документация подтверждает смысл полей, но не заменяет проверку конкретной операции и файловой системы.
По одному признаку выводить рано. Старый mtime не гарантирует старое содержимое: его можно сохранить при копировании или выставить отдельно. Свежий ctime говорит, что состояние inode менялось, но не раскрывает инициатора. Время рождения может отсутствовать вовсе.
Изолированный тест: смена прав и запись
Проверка выполнена 16 ноября 2026 года на GNU coreutils 9.7. Сценарий создаёт отдельный каталог вида /tmp/stat-times.XXXXXX, определяет все пути внутри него и удаляет только каталог, совпадающий с этим шаблоном. Файлы рабочего сервера не используются. В проверенной локальной файловой системе поддерживалось время рождения файла; переносить этот результат на NFS или другую файловую систему нельзя.
Сохраните сценарий как stat-times-lab.sh в отдельном тестовом каталоге. Для запуска достаточно обычного пользователя с правом записи в /tmp. Нужны Bash, GNU stat, touch, chmod, sleep, cat и rm.
#!/usr/bin/env bashset -euo pipefaillab_root="$(mktemp -d /tmp/stat-times.XXXXXX)"cleanup() { case "$lab_root" in /tmp/stat-times.??????) rm -rf -- "$lab_root" ;; *) printf 'Refusing cleanup outside the lab: %s\n' "$lab_root" >&2 ;; esac}trap cleanup EXITtarget_file="$lab_root/report.txt"snapshot() { label="$1" printf '=== %s ===\n' "$label" stat --printf='mode=%A\nsize=%s\nmtime=%y\nctime=%z\nbirth=%w\n' -- "$target_file"}printf 'alpha\n' >"$target_file"chmod 0644 -- "$target_file"touch -d '2026-01-02 03:04:05 UTC' -- "$target_file"snapshot initialsleep 1chmod 0600 -- "$target_file"snapshot after_chmodsleep 1printf 'beta\n' >>"$target_file"snapshot after_appendprintf '%s\n' '=== content ==='cat -- "$target_file"
Сначала проверяем синтаксис, затем запускаем лабораторию. Обработчик trap очищает только созданный временный каталог; после фактического прогона каталог отсутствовал.
bash -n stat-times-lab.sh
TZ=Europe/Moscow bash stat-times-lab.sh
Что изменилось в трёх снимках
Фактический прогон завершился с кодом 0. Ниже — его полный вывод; времена ctime и birth относятся только к этому запуску и не являются эталонными значениями для другой машины.
=== initial ===mode=-rw-r--r--size=6mtime=2026-01-02 06:04:05.000000000 +0300ctime=2026-11-16 05:47:20.449882971 +0300birth=2026-11-16 05:47:20.444145632 +0300=== after_chmod ===mode=-rw-------size=6mtime=2026-01-02 06:04:05.000000000 +0300ctime=2026-11-16 05:47:21.452168087 +0300birth=2026-11-16 05:47:20.444145632 +0300=== after_append ===mode=-rw-------size=11mtime=2026-11-16 05:47:22.456190349 +0300ctime=2026-11-16 05:47:22.456190349 +0300birth=2026-11-16 05:47:20.444145632 +0300=== content ===alphabeta
В начальном снимке mtime старше birth не из-за путешествия во времени: сценарий намеренно выставил mtime на 2 января командой touch. Это отдельный контрпример попытке определить возраст файла по одному mtime.
Поле | начальный снимок | после смены прав | после добавления данных |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
| без изменения |
|
|
|
|
|
|
| без изменения | без изменения |
После chmod изменился mode и сдвинулся ctime. Размер и mtime остались прежними: данные файла не переписывались. Это прямой контрпример чтению ctime как «времени создания».
После добавления строки beta размер вырос с 6 до 11 байт, а mtime и ctime изменились. Birth time остался прежним в этой файловой системе. Совпадение mtime и ctime до наносекунды в последнем снимке — наблюдение конкретного прогона, а не обещание одинаковых значений при любой записи.

Как использовать временные метки в расследовании
Зафиксируйте точный путь и сразу сохраните снимок метаданных командой
stat, не изменяя файл; включите часовой пояс и полную точность. Не выполняйтеtouch,chmodили редакторское сохранение на исследуемом файле.Сформулируйте гипотезу до просмотра журналов. Запись данных в файл должна согласоваться с
mtimeи обычно сctime; изменение прав может сдвинутьctimeбезmtime.Сопоставьте границу времени с независимыми свидетельствами: журналом приложения,
auditd, историей конфигурации, системой контроля версий, резервными копиями и контрольными суммами.Проверьте, не сохраняла ли используемая операция
mtime. Копирование, распаковка и восстановление имеют собственные параметры и не позволяют делать универсальный вывод по одной отметке.Если
birthравен дефису, запишите «неизвестно», а не подменяйте егоctime. Если значение есть, отдельно проверьте возможности файловой системы и инструмента.Сформулируйте вывод с границами: какое поле изменилось, между какими снимками и какое внешнее событие это подтверждает. Неустановленного автора или причину так и называйте неустановленными.
Отметка времени не проверяет содержимое резервной копии или архива. Если исходный каталог ещё доступен, используйте отдельную проверку, например сравнение tar-архива с исходным каталогом до очистки. Время помогает построить хронологию, а сравнение отвечает на другой вопрос — совпадают ли данные.
Границы метода
Поддержка
birth timeзависит от файловой системы, ядра и инструмента. Дефис в%w— допустимый результат; он не означает ошибку командыstat.Точность отметок времени различается. Округление в отчёте может сделать два разных события одинаковыми, поэтому исходный вывод лучше хранить полностью.
atimeможет обновляться лениво из-заrelatime,noatimeи других параметров. В этой лабораторииatimeне проверялся.На NFS и других сетевых файловых системах важны часы разных узлов, кэширование и реализация сервера. Локальный тест этого не подтверждает.
mtimeиctimeне содержат пользователя,PIDили текст операции. Для атрибуции нужны заранее настроенные журналы и аудит.Копирование, распаковка и восстановление могут создавать новый
inodeи при этом сохранять отдельные времена. Проверяйте фактическую команду и её параметры.
Критерий результата
Расследование можно считать завершённым, когда каждое утверждение связано с конкретным полем и независимым подтверждением. «Данные изменились» требует mtime и проверки содержимого или журнала; «права изменились» — ctime, mode и свидетельство операции; «файл создан тогда-то» — доступного birth time и понимания происхождения файла. Если подтверждения нет, корректный итог — граница времени и честное «причина неизвестна».
В лаборатории гипотезы совпали с наблюдением: chmod изменил ctime без mtime, а добавление данных изменило оба поля. На рабочем сервере повторять изменение ради красивого совпадения нельзя — сначала сохраняем состояние, затем проверяем журналы и данные. Спокойная хронология обычно полезнее одной очень уверенной даты.
Short answer: in GNU stat, the mtime field shows the time of the last data modification of the file, ctime shows the time of the last state change of inode, and birth shows the file birth time if the file system provides it. ctime does not indicate creation time. One timestamp sets a boundary for the investigation, but by itself it does not identify the user, process, or reason for the change.
For a readable snapshot, separate directives are required: %y for mtime, %z for ctime, and %w for birth time. If the birth time is unknown, %w outputs -. Preserve the time zone and fractional seconds: without them, comparing two snapshots is more difficult.
Capturing fields separately
First, check the utility version and the exact path. Separately determine whether the path is a symbolic link: without --dereference, GNU stat reads the metadata of the link itself, while with --dereference it reads the metadata of its target. The command below, without this parameter, only reads the metadata of the specified object. Substitute an existing file; do not modify its timestamps for an experiment on a production server.
stat --version
stat --printf='name=%n\nmode=%A\nsize=%s\nmtime=%y\nctime=%z\nbirth=%w\n' -- /path/to/file
In the output, timestamp values are not the only important fields. The mode and size fields help clarify exactly what changed, while the full path protects against comparing two files with the same name. For investigating a large directory tree, it is useful to additionally save device and inode, but these are separate fields and a separate question.
Field | What it records | What it does not prove |
|---|---|---|
| Last modification of file data | Which user or process wrote the data and exactly what changed |
| Last modification of | File creation time |
| File birth time, if the file system stores and serves it | That the file was not copied or restored |
| Last recorded access to the data | Each read: the update may be delayed or disabled |
The semantics of the directives are described in the GNU stat guide. The section GNU File timestamps explains when the timestamps themselves are updated and what limitations apply; Linux definitions are also provided in inode(7). Documentation confirms the meaning of the fields but does not replace verification of a specific operation and file system.
Relying on a single indicator is premature. An old mtime does not guarantee old content: it can be preserved during copying or set separately. A fresh ctime indicates that the state of inode has changed, but does not reveal the initiator. Birth time may be entirely absent.
Isolated test: changing permissions and writing
The check was performed on November 16, 2026, on GNU coreutils 9.7. The script creates a separate directory of the form /tmp/stat-times.XXXXXX, identifies all paths within it, and removes only the directory matching this pattern. Files from the working server are not used. The tested local file system supported file birth time; this result cannot be transferred to NFS or other file systems.
Save the script as stat-times-lab.sh in a separate test directory. To run it, a regular user with write permissions to /tmp is sufficient. Bash, GNU stat, touch, chmod, sleep, cat, and rm are required.
#!/usr/bin/env bashset -euo pipefaillab_root="$(mktemp -d /tmp/stat-times.XXXXXX)"cleanup() { case "$lab_root" in /tmp/stat-times.??????) rm -rf -- "$lab_root" ;; *) printf 'Refusing cleanup outside the lab: %s\n' "$lab_root" >&2 ;; esac}trap cleanup EXITtarget_file="$lab_root/report.txt"snapshot() { label="$1" printf '=== %s ===\n' "$label" stat --printf='mode=%A\nsize=%s\nmtime=%y\nctime=%z\nbirth=%w\n' -- "$target_file"}printf 'alpha\n' >"$target_file"chmod 0644 -- "$target_file"touch -d '2026-01-02 03:04:05 UTC' -- "$target_file"snapshot initialsleep 1chmod 0600 -- "$target_file"snapshot after_chmodsleep 1printf 'beta\n' >>"$target_file"snapshot after_appendprintf '%s\n' '=== content ==='cat -- "$target_file"
First, check the syntax, then run the lab. The trap handler cleans only the created temporary directory; after the actual run, the directory was absent.
bash -n stat-times-lab.sh
TZ=Europe/Moscow bash stat-times-lab.sh
What changed in the three snapshots
The actual run completed with code 0. Below is its full output; times ctime and birth apply only to this run and are not reference values for another machine.
=== initial ===mode=-rw-r--r--size=6mtime=2026-01-02 06:04:05.000000000 +0300ctime=2026-11-16 05:47:20.449882971 +0300birth=2026-11-16 05:47:20.444145632 +0300=== after_chmod ===mode=-rw-------size=6mtime=2026-01-02 06:04:05.000000000 +0300ctime=2026-11-16 05:47:21.452168087 +0300birth=2026-11-16 05:47:20.444145632 +0300=== after_append ===mode=-rw-------size=11mtime=2026-11-16 05:47:22.456190349 +0300ctime=2026-11-16 05:47:22.456190349 +0300birth=2026-11-16 05:47:20.444145632 +0300=== content ===alphabeta
In the initial snapshot, mtime is older than birth not because of time travel: the script intentionally set mtime to January 2 using the command touch. This is a separate counterexample to attempts to determine file age based on a single mtime.
Field | initial snapshot | after permission change | after data addition |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
| no change |
|
|
|
|
|
|
| no change | without change |
After chmod, mode changed and ctime shifted. The size and mtime remained the same: the file data was not rewritten. This is a direct counterexample to reading ctime as "creation time".
After adding the line beta, the size increased from 6 to 11 bytes, and mtime and ctime changed. Birth time remained the same in this file system. The match between mtime and ctime to the nanosecond in the last snapshot is an observation from a specific run, not a guarantee of identical values for any write.

How to Use Timestamps in an Investigation
Record the exact path and immediately save a metadata snapshot using the
statcommand without modifying the file; include the time zone and full precision. Do not runtouch,chmod, or perform an editor save on the file under investigation.Formulate the hypothesis before reviewing the logs. Writing data to a file must align with
mtimeand typically withctime; changing permissions can shiftctimewithoutmtime.Correlate the time boundary with independent evidence: the application log,
auditd, configuration history, version control system, backups, and checksums.Verify whether the operation in use preserved
mtime. Copying, unpacking, and restoring have their own parameters and do not allow drawing universal conclusions from a single timestamp.If
birthis a dash, record "unknown" rather than substituting it withctime. If a value exists, separately verify the capabilities of the file system and the tool.Formulate a conclusion with boundaries: which field changed, between which snapshots, and what external event confirms it. If the author or cause is unknown, state it as unknown.
A timestamp does not verify the contents of a backup or archive. If the source directory is still accessible, use a separate check, such as comparing the tar archive with the source directory before cleanup. Time helps build a chronology, while comparison answers a different question: do the data match?
Method Boundaries
Support for
birth timedepends on the file system, kernel, and tool. A dash in%wis a valid result; it does not indicate an error in thestatcommand.Timestamp accuracy varies. Rounding in a report can make two distinct events appear identical, so the original output should be preserved in full.
atimemay be updated lazily due torelatime,noatime, and other parameters. In this lab,atimewas not verified.On NFS and other network file systems, the clocks of different nodes, caching, and the server implementation are critical. A local test does not confirm this.
mtimeandctimedo not contain a user,PID, or operation text. Attribution requires pre-configured logs and audit trails.Copying, unpacking, and restoring can create a new
inodewhile preserving individual timestamps. Verify the actual command and its parameters.
Result Criteria
An investigation can be considered complete when every statement is linked to a specific field and independent confirmation. "Data changed" requires mtime and verification of content or logs; "permissions changed" requires ctime, mode, and evidence of the operation; "file created at that time" requires an available birth time and understanding of the file's origin. If no confirmation exists, the correct conclusion is a time boundary and an honest "cause unknown".
In the lab, the hypotheses matched the observation: chmod changed ctime without mtime, and adding data changed both fields. On the production server, repeating a change just to achieve a neat match is not allowed — first save the state, then check the logs and data. A calm chronology is usually more useful than a single, highly confident date.





Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.