Linux atime ctime mtime

IgorKa — Информационный ресурс

Немного обо всем и все о немногом, или практический опыт системного администратора.

Июль 2010
Пн Вт Ср Чт Пт Сб Вс
« Июнь Авг »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Временные параметры файла — atime mtime ctime

Решил я сегодня уточнить значения параметров mtime, atime и ctime, которые присутствуют у каждого файла в Linux. На первый взгляд все вроде понятно:

mtimemodification time — время последней модификации (изменения) файла
atimeaccess time — время последнего доступа к файлу
ctimechange time — время последнего изменения атрибутов файла (данных которые хранятся в inode-области)

Но когда начинаешь спрашивать себя когда меняются эти параметры, в частности какие команды меняют их, а какие нет, и проверять на практике ответы на свои же вопросы — все не так очевидно. Особенно для каталогов, которые тоже являются разновидностью файлов в Linux. Вот решил поделится некоторыми экспериментами в этом направлении. Эксперименты проводил конечно же в своей Ubuntu 9.10 c файловой системой ext4. У ext4, кстати появилось два дополнительных временных параметра — время создания файла linux и время удаления файла linux, но о них в самом конце.

До начала своих экспериментов я предполагал следующее.
Параметр mtime — изменяется после того как изменяется содержимое файла. Например, открыли файл командой nano, дописали что-то, сохранили, закрыли, и время mtime поменялось. А как в случае с каталогами? Предполагал, что время модификации для каталога изменяется когда в каталоге создаются/удаляются файлы и подкаталоги.

Параметр atime — изменяется тогда, когда мы получаем доступ к файлу, например, той же командой nano мы получаем доступ к файлу. Значит atime должен измениться. Команды cat, less, tail выводят содержимое файла, значит мы получаем доступ к нему, но не меняем его поэтому mtime меняться не должен. А как быть с каталогами? Когда меняется atime для каталога? Тут я даже не знал, что себе ответить.

Параметр ctime — самый простой для моего понимания. Изменяется тогда когда изменяются права доступа к файлу (командой chmod), изменяется владелец файла (команда chown), создаются жесткие ссылки на файл (команда ln). В этом плане различий с каталогом нет, с той лишь разницей, что на каталоги нельзя создавать жесткие ссылки.

Вот примерно так я понимал значение временных параметров файлов. Практические эксперименты несколько расширили и изменили мои познания. Во время экспериментов проверку временных параметров проверял командой stat, которая показывает сразу все три временных атрибута. Если использовать команду ls, то по умолчанию она выводит время mtimels -l. ls -lu (или ls –time=atime|access|use) — выводит время atime — время последнего доступа к файлу. ls -lc (или ls –time=ctime|status) — выводит время ctime — время последнего изменения атрибутов.

Начал с параметра atime. Создаю в домашнем каталоге, каталог timetest и проверяю его временные метки командой stat (вывод результата сокращаю для экономии места):

Сейчас все временные метку равны друг другу так и должно быть. Далее захожу в каталог timetest и создаю пустой файл test, после чего проверяю временные метки каталога:

Источник

File Timestamps – mtime, ctime and atime in Linux

Timestamps are records for the times in which actions are performed on files. A timestamp is useful because it keeps records of when a file was accessed, modified, or added. Linux’s files have 3 timestamps recorded by the computer:

  • Access timestamp (atime): which indicates the last time a file was accessed.
  • Modified timestamp (mtime): which is the last time a file’s contents were modified.
  • Change timestamp (ctime): which refers to the last time some metadata related to the file was changed.

In Linux, a timestamp is actually stored as a number of seconds instead of a date and time. This number of seconds refers to the amount of time since 00:00:00 on January 1, 1970, which is the time of Unix Epoch. However, when a user wants a timestamp to be displayed, Linux will translate it to a human-readable format, so it is displayed as a date and time. Users can view timestamps using ls command or stat command.

mtime:

Modified timestamp (mtime) indicates the last time the contents of a file were modified. For example, if new contents were added, deleted, or replaced in a file, the modified timestamp is changed. To view the modified timestamp, we can simple use the ls command with -l option.

ctime:

Unlike mtime, which is only related to the contents inside a file, changed timestamp indicates the last time some metadata of a file was changed. For example, if permission settings of a file were modified, mtime will indicate it. To see the changed timestamp, we can use -lc option with the ls command as follows:

atime:

Acces timestamp (atime) refers to the last time a file was read by a user. That is, a user displayed the contents of a file using any suitable program, but did not necessarily modify anything. To view an access timestamp using ls command, we use -lu option followed by the file name.

stat command:

stat command can be used to see all timestamps of a file simultaneously.

Comparison Table

The table below summarizes the difference between the three timestamps we mentioned:

File Contents are Modified Metadata is Modified File Accessed without Modification Command to Use
mtime Changes No change No change ls -l or stat
ctime Changes Changes No change ls -cl or stat
atime Changes No change Changes ls -ul or stat

To further explain the concept, we will examine a file named test.txt, the following changes were made to the file:

Creating the File

The file was created at 14:04 on 25/03/2021 using the nano command. We can also use the touch command or any text editor. Initially, we added 1 line to the file

Command to create file:

Initially, the timestamps all show the time in which the file was created. The image below shows an example of using the stat command to view the 3 timestamps. In this image, the initial timestamps, which show the time that the file was created, are shown. The number +004 at the right of each timestamp is known as time zone offset, which indicates that the time zone is +004 hours ahead of UTC. The displayed date and time are converted from UTC to the local time zone when displayed to the user. We can also notice that stat command is highly exact in showing the seconds in a timestamp.

Command:

Alternatively, ls command can be used to view each timestamp individually as follows:

Command:

In the following steps, we will make some changes in the file and observe the change in timestamps using stat command. ls command can be used as well.

Modifying the File

The file was accessed and a new line was added to it at 14:22 on 25/03/2021 using nano text editor (any text editor can be used).

Command:

Using stat command, we can see that all 3 timestamps were changed to 14:22.

Command:

Changing Metadata

The file’s permissions were changed at 14:36 on 25/3/2021 using chmod command.

Command:

We notice that after changing the permissions, both ctime and atime changed to 14:36. This is not the case with mtime since it only changes when the contents inside the file are modified. Therefore, mtime is still at 14:22.

Command:

Opening the File without Making Changes

The file was opened in nano text editor, but no changes were made at 14:55 on 25/3/2021.

Command:

From the output of stat command, we can observe that the only timestamp that changed to 14:55 is the access timestamp. This is because no data was changed. Therefore, ctime remains at 14:36 while mtime remains at 14:22.

Источник

File Timestamps — mtime, ctime and atime in Linux

When you are working with directory and files, you may need to know about Linux file timestamps such as change time (ctime), access time (atime), and modification time (mtime). Linux files, directories, sockets have three different timestamps – mtime, ctime and atime.

Probably when working in Linux you have get answers to following questions:

When was the last date of file content modified? When was the file last opened/accessed ? When the properties of the file such as ownership, permissions last changed?

Here, we are going to explain each file timestamps in Linux in detail.

mtime – Last modification time

Mtime or modification time is the time of the last change to the file contents. ‘Modification’ means something inside the file was amended or deleted, or new data was added.

Use the -l (long listing) option with ls, you can see the modified timestamp.

ctime – last change time

Ctime is the changed timestamp referring to changes made to attribute of a file such as ownership, access permission. It’s the time at which the metadata related to the file changed.

To see the change timestamp, use the -lc option:-

atime – last access time

Atime or access timestamp is the last time a file was read, read by one of the processes directly or through commands and scripts.

Use the -lu (access time) option with command ls to see access time. You can see the modification time and access time for the same file are different.

Show mtime, atime and ctime with stat command

Most of the linux distribution come with stat command which can be used to show all of the time stamp in a more convenient way.

To see modification time, access time and change time of a particular file use as follow:-

The timestamp are first generated in number of seconds since the Unix epoch, it translates the number of seconds into a date and time from the system time zone.

Conclusion

Unfortunately, we won’t be able to find file creation time using ctime, atime or mtime orelse we have to use debugfs command.

In this article, we learned about Linux file timestamps and about access time, modification time, and change time. Your feedback is much welcome.

Источник

atime, ctime and mtime in Unix filesystems

As you know, Unix filesystems store a number of timestamps for each file. This means that you can use these timestamps to find out when any file or directory was last accessed (read from or written to), changed (file access permissions were changed) or modified (written to).

File and directory timestamps in Unix

Three times tracked for each file in Unix are these:

  • access time – atime
  • change time – ctime
  • modify time – mtime

INTERESTING: there’s no file creation timestamp kept in most filesystems – meaning you can’t run a command like “show me all files created on certain date”. This said, it’s usually possible to deduce the same from ctime and mtime (if they match – this probably means that’s when the file was created).

atime – Last Access Time

Access time shows the last time the data from a file or directory was accessed – read by one of the Unix processes directly or through commands and scripts.

Due to its definition, atime attribute must be updated – meaning written to a disk – every time a Unix file is accessed, even if it was just a read operation. Under extreme loads, atime requirement could severely impact the filesystem performance, especfially with hard disks (HDDs) compared to Solid State Disks (SSDs).

Modern Unix and Unix like operating systems have special mount options to optimise atime usage (or disable it completely).

For instance, in Linux kernel the following atime optimisations are supported when mounting filesystem:

  • strictatime – always update atime (no longer the default!)
  • relatime (“relative atime”) – selective atime updates, usually if previous — atime is an older timestamp than ctime and mtime (see below)
  • nodiratime – no access time updates for directories (files still get atime updates)
  • noatime – no access time updates for anything

ctime – Last Change Time

ctime shows when your file or directory got metadata changes – typically that’s file ownership (username and/or group) and access permissions. ctime will also get updated if the file contents got changed.

mtime – Last Modification Time

Last modification time shows time of the last change to file’s contents. It does not change with owner or permission changes, and is therefore used for tracking the actual changes to data of the file itself.

INTERESTING: When a new file or directory is created, usually all three times – atime, ctime and mtime – are configured to capture the current time.

How to Use atime, ctime and mtime

Lots of common system administration tasks can be helped, if not completed, using knowledge of atime, ctime and mtime attributed:

  • find files updated on a certain date
  • confirm when was the last time a configuration file was changed
  • find files modified in the last hour or day – very useful for finding most recently updated log files
  • verify if a certain file was accessed and when – useful when debugging a script
  • quickly get the list of really old files (not updated for longer than 30 days or something like that)
  • confirm when the directory was updated – can suggest that temporary files were created and quickly deleted, so you don’t see the files but recognise evidence when they were still in the directory
  • review a list of files to confirm when they had ownership (user/group) data updated and if this time is different from file modifications – could be useful when reviewing security breach on your Unix system

Find atime, ctime and mtime with ls

The simplest way to confirm the times associated with a file is to use ls command. Timestamps are shown when using the long-format output of ls command, ls -l:

This is the default output of

ls -l, which shows you the time of the last file modification – mtime. In our example, file /tmp/file1 was last changed around 7:10am. If we want to see the last access time for this file, atime – you need to use -lu options for ls. The output will probably show some later time:

In the example, it’s 7:27am.

Lastly, ls -lc will show you the last time our file was changed, ctime:

To show you how this works, I’ll change the ownership of the file and then run the same 3 ls commands to show you that only the ctime had been updated. I run the date command just before doing anything else so that you can compare the times:

Show atime, ctime and mtime with stat command

In Linux distributions, you will probably find a stat command, which can be used to show all of the times in a more convenient way, and among plenty of other useful information about your file:

Источник

Читайте также:  Стандартный солитер для windows
Оцените статью