- 🐧 Как узнать время и дату изменения файла в системах Linux
- Получение даты последнего изменения файла в Linux с помощью команды date
- Получение даты последнего изменения файла в Linux с помощью команды ls
- Получение даты последнего изменения файла в Linux с помощью команды stat
- Получение даты последнего изменения файла в Linux с помощью команды midnight commander
- Заключение
- How to Get Last Modified Date of File in Linux
- 1. Using stat command
- 2. Using date command
- 3. Using ls -l command
- 4. Using httpie
- Output
- Conclusion
- More Articles You May Like
- 1 thought on “How to Get Last Modified Date of File in Linux”. add one
- How to check all timestamps of a file?
- 2 Answers 2
- 1. atime
- 2. ctime
- 3. mtime
- How to display modification time of a file?
- 2 Answers 2
- 🐧 Как узнать дату последнего изменения файла на Linux
- 1. Использование команды stat
- 2. Использование команды date
- 3. Использование команды ls -l
- 4. Использование httpie
- Заключение
🐧 Как узнать время и дату изменения файла в системах Linux
В этом туториале показаны 4 простых способа получения даты последнего изменения файла в Linux.
Прочитав это руководство, вы будете знать, как проверить дату последней модификации файла с помощью команд ls, date и stat и бонус метод с MC.
Получение даты последнего изменения файла в Linux с помощью команды date
Первый способ узнать дату последней модификации файла в Linux, описанный в этой статье, основан на команде date.
Когда за командой date следует флаг -r, она показывает нам дату последней модификации файла.
Следующий пример показывает синтаксис для использования команды date, где itisgood – файл, дату последней модификации которого я хочу вывести.
Как вы можете видеть, вывод очень удобен для пользователя и включает дату и время последней модификации файла.
Для получения дополнительной информации о команде date посетите сайт https://man7.org/linux/man-pages/man1/date.1.html.
Получение даты последнего изменения файла в Linux с помощью команды ls
Второй метод, описанный в этом руководстве, объясняет, как получить дату последнего изменения файла с помощью команды ls.
Сначала используем команду ls с флагом -l, как показано на скриншоте ниже.
Флаг -l указывает команде ls вывести список файлов в длинном формате.
Список в длинном формате включает дату последней модификации файла.
Как вы можете видеть, в первом столбце показаны права, во втором и третьем – пользователи и группы файлов.
Четвертый столбец – размер.
Затем вы можете увидеть месяц, день и время, когда файл был изменен.
В отличие от предыдущего метода с ls, вы получите список всех файлов в каталоге, включая даты их модификации.
Для упорядоченного вывода вы можете добавить флаг -t.
Флаг -t выведет упорядоченный по дате модификации вывод, показывая сначала последние измененные файлы.
как вы видите, последние измененные файлы теперь отображаются первыми.
Команда ls также позволяет проверить дату последней модификации файла по отдельности; для этого просто укажите имя файла, как показано ниже.
Получение даты последнего изменения файла в Linux с помощью команды stat
Третий метод получения даты последней модификации файла в Linux, описанный в этой статье, показывает, как использовать команду stat для достижения этого результата.
Синтаксис довольно прост; просто запустите команду stat, за которой следует имя файла, дату последнего изменения которого вы хотите узнать, как показано в примере ниже.
Как вы можете видеть, вывод показывает больше информации, чем предыдущие команды.
Важно различать даты модификации и изменения.
Строка с именем Modify показывает последний раз, когда файл был изменен.
Строка с именем Change показывает последний раз, когда статус файла изменился; статус включает изменение прав, изменение владельца и т.д.
Вы можете выполнить приведенную ниже команду, чтобы получить в выводе только время модификации, опуская остальную информацию.
Получение даты последнего изменения файла в Linux с помощью команды midnight commander
Вы также можете запустить mc в каталоге, где лежит нужный нам файл и посмотреть дату изменения:
Заключение
Это руководство показывает, что получить дату последнего изменения файла в Linux можно с помощью различных простых методов.
Ни один из описанных методов не имеет особых преимуществ; все они могут быть реализованы легко и без установки дополнительных пакетов.
Для этого руководства я использовал Debian, но все описанные здесь команды доступны во всех дистрибутивах Linux.
Все описанные команды имеют дополнительные возможности, о которых вы можете узнать, прочитав man-страницы, указанные в конце каждого раздела.
Источник
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.
More Articles You May Like
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.
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»
Источник
How to check all timestamps of a file?
Is there a command in Linux to check all timestamps of a file?
I’m trying to see the last modified, created, and touched dates on the file.
2 Answers 2
The command is called stat .
If you want to adjust the format, refer to the man pages, since the output is OS-specific and varies under Linux/Unix.
Generally, you can get the times through a normal directory listing as well:
- ls -l outputs last time the file content was modified, the mtime
- ls -lc outputs last time of file status modification, the ctime (What’s the difference?)
- ls -lu outputs last access time, the atime (although the usefulness of this concept is subject to discussion)
And of course, ctime does not record when a file was «created». The POSIX specification defines only three timestamps, but some Linux filesystems store Birth Time/Creation Time. How to find creation date of file? On such a supported configuration, one could use
There are only THREE distinct times values stored for each of your files, as defined by the POSIX Standard : http://pubs.opengroup.org/onlinepubs/9699919799/ (see Base Definitions section -> 4. General Concepts -> 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 .
Following examples show the difference among the atime, mtime and ctime, these examples are in GNU/Linux BASH. You can use stat -x in Mac OS X or other BSD Dist. to see the similar output format.
When the file just be created, three timestamps are the same.
1. atime
First, let’s access the file’s data by reading it ( less or vim ), printing it out ( cat ) or copy it to another file ( cp ).
2. ctime
Now let’s change the file status, by changing the permission ( chmod ) or renaming it ( mv )
Note that until now, the contents (data) of the file is still the same as when it created.
3. mtime
Finally, let’s modify the contents of the file by editing the file.
Источник
How to display modification time of a file?
I’d like a method to find and print the modified time of a file, for use within a bash script.
I have come up with:
Though I’d like to avoid parsing ls , also it’d be useful to have the year in there.
Ideally I’d like to see an output similar to the default output of the date command.
What other useful methods are available?
2 Answers 2
Don’t use ls , this is a job for stat :
-c lets us to get specific output, here %y will get us the last modified time of the file in human readable format. To get time in seconds since Epoch use %Y :
If you want the file name too, use %n :
Set the format specifiers to suit your need. Check man stat .
Example:
If you want the output like Tue Jul 26 15:20:59 BST 2016 , use the Epoch time as input to date :
Check date ‘s format specifiers to meet your need. See man date too.
but if the date is less than 10 it misses the time. This because of the extra space before the date if less than 10. Try this:
The awk command prints the fields separated by all spaces (-F ‘ ‘). Hope it works. I know this doesn’t answer the original question but just a clarification on the ls command for just date and time. When you Google «ubuntu get date and time of file» it lists this question at the top, which is what I was looking for, since I don’t need the year also. For year, date and time, you could try one of the commands below. %m prints month number. %b prints month abbreviation: Drop the %H:%M if you don’t need the hour and minute. %-d doesn’t print leading zero for the day of the month.
Источник
🐧 Как узнать дату последнего изменения файла на Linux
Иногда вам может потребоваться проверить подробную информацию о файле (отметку времени), например дату его последнего изменения.
Это может пригодиться, когда вы хотите проверить, когда этот файл последний раз редактировался.
Кроме того, это гарантирует, что у вас установлена последняя версия файла.
В этой статье вы узнаете 4 способа узнать дату последнего изменения файла в Linux.
1. Использование команды stat
Команда ls -l дает вам основную информацию о файле, такую как права собственности на файл и разрешения, размер файла и дата создания.
Команда stat возвращает атрибуты файла с подробной информацией, например, когда последний раз открывался и изменялся файл.
Синтаксис довольно простой.
После stat следует имя файла или полный путь к этому файлу.
Из вышеприведенного вывода мы можем ясно увидеть, когда к файлу в последний раз обращались (Дата доступа), Дату изменения, Дату изменения других параметров.
Если вы хотите просмотреть только дату изменения и опустить всю остальную информацию, выполните следующую команду:
2. Использование команды date
Команда date в основном синтаксисе отображает текущую дату.
Однако при использовании с параметром -r вы можете отобразить дату последней модификации файла, как показано далее:
3. Использование команды ls -l
Команда ls -l обычно используется для отображения дополнительной информации о файлах, например права собственности на файл и права доступа, размер и дата создания.
Чтобы перечислить и отобразить время последнего изменения, используйте параметр lt, как показано далее.
4. Использование httpie
Другой способ проверить дату последнего изменения – использовать клиентский инструмент командной строки httpie.
Инструмент обычно используется для взаимодействия с HTTP-серверами и API-интерфейсами, а также может проверять, когда последний раз был изменен файл, находящийся на веб-сервере.
Но сначала вам нужно установить его с помощью команды:
Ubuntu / Debian / Mint:
Чтобы проверить, когда последний раз был изменен файл на веб-сервере, используйте синтаксис:
Заключение
На этом статья завершается.
В этом руководстве мы описали различные способы, с помощью которых вы можете узнать дату последнего изменения файла в системе Linux и даже файла, размещенного на веб-сервере, с помощью инструмента httpie.
Надеюсь, у вас не возникнет проблем с просмотром времени последнего изменения файлов.
Источник