Linux get file time

How to Get Last Modified Date of File in Linux

Sometimes, you may be required to check detailed information about a file (timestamp) such as its last modified date. This can come in handy when you want to check when the file was last edited. Additionally, it ensures that you have the latest version of the file.

In this article, you will learn 4 ways to get the last modified date of file in Linux.

1. Using stat command

The ls -l command is just okay in giving you basic information about a file such as file ownership and permissions, file size, and creation date. The stat command returns detailed information file attributes such as the last time the file was accessed and modified.

The syntax is quite simple. stat is followed by the file name or the full path to the file.

From the above output, we can clearly see when the file was last accessed ( Access date ), Modify date, Change date among other parameters.

If you wish to view the modified date only and leave out all the other information, run the following command:

The -c option is used to return the date in a custom format, while the ‘%y’ flag displays the last modification time. For directories, the syntax remains the same. Simply replace the file name with that of the directory.

2. Using date command

The date command in its basic syntax displays the current date. However, when used with the -r option, you can display the last modification date of a file as shown.

3. Using ls -l command

The ls -l command is usually used for long listing — display additional information about a file such as file ownership and permissions, size and creation date. To list and display the last modified times, use the lt option as shown.

4. Using httpie

Another way you can check the last modified date is by using the httpie HTTP command-line client tool. The tool is usually used for interacting with HTTP servers and APIs and can also check when a file residing on a web server was last modified.

But first, you need to install it using the command:

On Ubuntu / Debian / Mint, run the command:

To check when a file on a web server was last modified, use the syntax:

Output

Conclusion

This wraps up this article. In this guide, we have featured various ways that you can use to list the last modified date of a file on a Linux system, and even a file hosted on a web server using the httpie tool. Hopefully, you won’t have an issue viewing when files were last modified.

1 thought on “How to Get Last Modified Date of File in Linux”. add one

I prefer using ‘ls’ over all the others because ls allows you to control precisely how the date and time are displayed. I believe stat only gives the choice between seconds-since-epoch and human-readable, with no control over the human-readable format.

Читайте также:  Как переустановить windows 2020

For ls, the relevant option is ‘—time-style’ and its format specifiers are fairly straightforward, using the same specifiers used by /bin/date. See ‘man date’ for all the available specifiers. My personal favorite is —time-style=»+%Y-%m-%d %H:%M:%S». I use this alias for my day-to-day ls needs.

alias l=»/bin/ls —time-style=\»+%Y-%m-%d %H:%M:%S\» —group-directories-first -lLFAGv»

Источник

Get file creation time on Linux with EXT4 edit

Linux offers three timestamps for files: time of last access of contents (atime), time of last modification of contents (mtime), and time of last modification of the inode (metadata, ctime).

You may recover the file creation date if you deal with capble filesystem like EXT4 — journaling file system for Linux:

… Ext4 provides timestamps measured in nanoseconds. In addition, ext4 also adds support for date-created timestamps.

But there no consensus in the community on that so

… as Theodore Ts’o points out, while it is easy to add an extra creation-date field in the inode (thus technically enabling support for date-created timestamps in ext4), it is more difficult to modify or add the necessary system calls, like stat() (which would probably require a new version) and the various libraries that depend on them (like glibc). These changes would require coordination of many projects. So even if ext4 developers implement initial support for creation-date timestamps, this feature will not be available to user programs for now.

Let’s wait five years and see if there is actually any consensus on it being needed and used at all, rather than rush into something just because “we can”.

So what to do? Let’s chill out

Now let’s question yourself how would you extract this information? We end up with the STAT utility

Источник

File Timestamps in Linux: atime, mtime, ctime Explained

In Linux, every file has some timestamps that provide some crucial analytics about when the file or its attributes were modified or changed. Let’s see these timestamps in detail.

What are Linux timestamps?

Any file in Linux has typically these three timestamps:

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

atime

atime stands for access time. This timestamp tells you when was the last time the file was accessed. By access, it means if you used cat, vim, less or some other tool to read or display the content of the file.

mtime

mtime stands for modify time. This timestamp tells you when was the last time the file was modified. By modify, it means if the contents of a file were changed by editing the file.

ctime

ctime stands for status change time. This timestamp tells you when was the last time the property and metadata of the file were changed. The metadata includes file permissions, ownership, name and location of the file.

How to see the timestamps of a file?

You can use the stat command to see all the timestamps of a file. Using stat command is very simple. You just need to provide the filename with it.

The output will be like this:

You can see all three timestamps (access, modify and change) time in the above output. All three timestamps are the same here because I just created this empty file with touch command.

Now let’s modify these timestamps.

If I use the less command to read the file, it will change only the access time because the content and metadata of the file remain the same.

Читайте также:  Windows 10 2004 compact full by flibustier 2021

Now let’s change the modify time. I’ll use cat command to add new text to this file. This will prevent the change in access time.

Did you notice something weird? You modified the file and expected the mtime to be changed but it also changed the ctime.

Remember, ctime is always changed with mtime. It’s because while mtime is under the control of user, ctime is controlled by the system. It represents when the last time the data blocks or metadata of a file was changed. If you modify the file, the data blocks change and thus ctime is changed.

You can change ctime alone by modifying file permissions using chmod or chgrp commands but you cannot modify mtime without modifying ctime.

You can also not change ctime in the past by normal means. It is a kind of security feature because it tells you the last time the file was changed. Even if someone modifies mtime and set it in the past for malicious purposes, ctime will indicate the actual time when the mtime was changed.

Remember: ctime will always be modified by mtime change.

What are the usage of file timestamps?

It helps a lot in analyzing. There could be a number of situations where you need to refer to the timestamps of a file. For example, you can see if a file was modified recently or not when it was supposed to be modified.

One of my favorite use was to locate log files of an application with mtime. Run the application and just go into the parent directory of the application and search for the files that have been modified in last few minutes.

I already showed you above that it can also help in analyzing if someone accessed the files or modified it maliciously. Timestamps play an important role in such situations.

How to know when a file was originally created?

Did you notice the last line of stat command output? It says ‘Birth’. You may guess that this represents the timestmap when the file was ‘born’ (or created to be more precise).

Actually, there is one more timestamp called creation time (cr). Not all filesystems support this timestamp. Ext4 is one of the popular Linux filesystems and though it supports the creation timestamp, the stat command at present is not able to show it. Maybe the future versions of stat command will show the creation timestamp in the Birth section.

Источник

ls —full-time + время создания файла

Как добавить в вывод `ls —full-time` время создания файлов (ctime)?

Какой-то непонятный у ls мануал.

Хочу ещё одну колонку (точнее две) с датой и временем создания файлов.

ctime — это не время создания файла.
Время создания файла не хранится. Или хранится, но далеко не на всех файловых системах.

ls не будет выводить две даты, мучайте find.

Ну, а то что ctime это «time of last modification of file status information» написано в man’е.

Люникс огорчает в 10001 раз.

А кто, кроме вендов, может порадовать по этому поводу?

Таки UFS2, оказывается, может.

Это же FreeBSD, не?

В таком случае тебе нужен не ls, a stat

man stat, надеюсь он понятнее чем man ls

Сергей, нет в Люникс VFS даты создания файла. Забейте 😉

Она самая и данная фича труднопереносима между ФС.

Ты зачем пришел? В ext4 есть такое поле. Кому надо доберется.

man stat для вывода нескольких полей даты.

А вот в исходниках, да, есть:

Gnulib already supports the code for reading Btime (aka ext4’s crtime, aka birth-time) from all file systems that support it (at least ext4 and NTFS). It’s just that no one has yet written the code to make stat(1) take advantage of this code in the stat-times module.

Вот ведь, б*дь, 1001 пример того, что ядерные фифи в userspace отсутствуют.

Читайте также:  Вырезать папку mac os

Как же это через одно место.

Через debugfs я знал, но говорить не хотел, ты и так полон ненависти к непонятному.

Я полон ненависти к не user-friendly ОСям, которые нужные вещи прячут глубоко в опу.

Я полон ненависти к разрабам GNU, которые простейшую фичу уже лет 10 не могут реализовать.

Скрипт, который рекурсивно выводит modification creation time для заданной директории. Файлы, содержащие в имени перевод строки, не поддерживаются. Впрочем, мне плевать на таких извращенцев.

Источник

5 Linux Touch Command Examples (How to Change File Timestamp)

Every file in Linux is associated with timestamps, which specifies the last access time, last modification time and last change time.

Whenever we create a new file, or modify an existing file or its attributes, these timestamps will be updated automatically.

Touch command is used to change these timestamps (access time, modification time, and change time of a file).

1. Create an Empty File using touch

You can create an empty file using touch command. The following example will create a zero byte new file named tgs.txt.

You can also use -c option to avoid creating new files. If you use -c option, and if a file doesn’t exists, touch will not create the file.

Commands like ls command and find command uses these timestamp information for listing and finding files.

You can also create more than 1 files from a single touch command. The following example will create 4 files named a, b, c, and d.

2. Change File’s Access Time using -a

We can change the access time of a file using -a option. By default it will take the current system time and update the atime field.

Before touch command is executed:

After the above touch command (Please note that the access time is changed):

3. Change File’s Modification Time using -m

You can change the modification time of a file using -m option.

The above method can be used to change the mtime of all obj files, when using make utility.

NOTE: It is not possible to change the ctime using touch command

4. Explicitly Setting Access and Modification time using -t and -d

Instead of taking the current time-stamp, you can explicitly specify the time using -t and -d options.

The format for specifying -t is [[CC]YY]MMDDhhmm[.SS]

The following explains the above format:

  • CC – Specifies the first two digits of the year
  • YY – Specifies the last two digits of the year. If the value of the YY is between 70 and 99, the value of the CC digits is assumed to be 19. If the value of the YY is between 00 and 37, the value of the CC digits is assumed to be 20. It is not possible to set the date beyond January 18, 2038.
  • MM – Specifies the month
  • DD – Specifies the date
  • hh – Specifies the hour
  • mm – Specifies the minute
  • SS – Specifies the seconds

Verify the above change using stat command:

You can also use a string to change the time

For developers, touch command will be really helpful when you are working with Makefiles

5. Copy the Time-stamp from Another File using -r

You can also take a file as a reference, and update the time for other files, so that both file will hold the same time.

Источник

Оцените статью