Get information about file linux

Unix / Linux — File Management

In this chapter, we will discuss in detail about file management in Unix. All data in Unix is organized into files. All files are organized into directories. These directories are organized into a tree-like structure called the filesystem.

When you work with Unix, one way or another, you spend most of your time working with files. This tutorial will help you understand how to create and remove files, copy and rename them, create links to them, etc.

In Unix, there are three basic types of files −

Ordinary Files − An ordinary file is a file on the system that contains data, text, or program instructions. In this tutorial, you look at working with ordinary files.

Directories − Directories store both special and ordinary files. For users familiar with Windows or Mac OS, Unix directories are equivalent to folders.

Special Files − Some special files provide access to hardware such as hard drives, CD-ROM drives, modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and enable you to access a single file using different names.

Listing Files

To list the files and directories stored in the current directory, use the following command −

Here is the sample output of the above command −

The command ls supports the -l option which would help you to get more information about the listed files −

Here is the information about all the listed columns −

First Column − Represents the file type and the permission given on the file. Below is the description of all type of files.

Second Column − Represents the number of memory blocks taken by the file or directory.

Third Column − Represents the owner of the file. This is the Unix user who created this file.

Fourth Column − Represents the group of the owner. Every Unix user will have an associated group.

Fifth Column − Represents the file size in bytes.

Sixth Column − Represents the date and the time when this file was created or modified for the last time.

Seventh Column − Represents the file or the directory name.

In the ls -l listing example, every file line begins with a d, , or l. These characters indicate the type of the file that’s listed.

Regular file, such as an ASCII text file, binary executable, or hard link.

Block special file. Block input/output device file such as a physical hard drive.

Character special file. Raw input/output device file such as a physical hard drive.

Directory file that contains a listing of other files and directories.

Symbolic link file. Links on any regular file.

Named pipe. A mechanism for interprocess communications.

Socket used for interprocess communication.

Metacharacters

Metacharacters have a special meaning in Unix. For example, * and ? are metacharacters. We use * to match 0 or more characters, a question mark (?) matches with a single character.

Displays all the files, the names of which start with ch and end with .doc

Here, * works as meta character which matches with any character. If you want to display all the files ending with just .doc, then you can use the following command −

Hidden Files

An invisible file is one, the first character of which is the dot or the period character (.). Unix programs (including the shell) use most of these files to store configuration information.

Some common examples of the hidden files include the files −

.profile − The Bourne shell ( sh) initialization script

.kshrc − The Korn shell ( ksh) initialization script

.cshrc − The C shell ( csh) initialization script

.rhosts − The remote shell configuration file

To list the invisible files, specify the -a option to ls

Single dot (.) − This represents the current directory.

Double dot (..) − This represents the parent directory.

Creating Files

You can use the vi editor to create ordinary files on any Unix system. You simply need to give the following command −

The above command will open a file with the given filename. Now, press the key i to come into the edit mode. Once you are in the edit mode, you can start writing your content in the file as in the following program −

Once you are done with the program, follow these steps −

Press the key esc to come out of the edit mode.

Press two keys Shift + ZZ together to come out of the file completely.

You will now have a file created with filename in the current directory.

Editing Files

You can edit an existing file using the vi editor. We will discuss in short how to open an existing file −

Once the file is opened, you can come in the edit mode by pressing the key i and then you can proceed by editing the file. If you want to move here and there inside a file, then first you need to come out of the edit mode by pressing the key Esc. After this, you can use the following keys to move inside a file −

l key to move to the right side.

h key to move to the left side.

k key to move upside in the file.

j key to move downside in the file.

So using the above keys, you can position your cursor wherever you want to edit. Once you are positioned, then you can use the i key to come in the edit mode. Once you are done with the editing in your file, press Esc and finally two keys Shift + ZZ together to come out of the file completely.

Display Content of a File

You can use the cat command to see the content of a file. Following is a simple example to see the content of the above created file −

You can display the line numbers by using the -b option along with the cat command as follows −

Counting Words in a File

You can use the wc command to get a count of the total number of lines, words, and characters contained in a file. Following is a simple example to see the information about the file created above −

Here is the detail of all the four columns −

First Column − Represents the total number of lines in the file.

Second Column − Represents the total number of words in the file.

Third Column − Represents the total number of bytes in the file. This is the actual size of the file.

Fourth Column − Represents the file name.

You can give multiple files and get information about those files at a time. Following is simple syntax −

Copying Files

To make a copy of a file use the cp command. The basic syntax of the command is −

Following is the example to create a copy of the existing file filename.

You will now find one more file copyfile in your current directory. This file will exactly be the same as the original file filename.

Renaming Files

To change the name of a file, use the mv command. Following is the basic syntax −

The following program will rename the existing file filename to newfile.

The mv command will move the existing file completely into the new file. In this case, you will find only newfile in your current directory.

Deleting Files

To delete an existing file, use the rm command. Following is the basic syntax −

Caution − A file may contain useful information. It is always recommended to be careful while using this Delete command. It is better to use the -i option along with rm command.

Following is the example which shows how to completely remove the existing file filename.

You can remove multiple files at a time with the command given below −

Standard Unix Streams

Under normal circumstances, every Unix program has three streams (files) opened for it when it starts up −

stdin − This is referred to as the standard input and the associated file descriptor is 0. This is also represented as STDIN. The Unix program will read the default input from STDIN.

stdout − This is referred to as the standard output and the associated file descriptor is 1. This is also represented as STDOUT. The Unix program will write the default output at STDOUT

stderr − This is referred to as the standard error and the associated file descriptor is 2. This is also represented as STDERR. The Unix program will write all the error messages at STDERR.

Источник

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.

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»

Источник

Команда file в Linux

Команда file — одна из самых полезных, поскольку позволяет узнать тип данных, которые на самом деле содержатся внутри документа. Если у вас есть какой-либо файл, взятый из ненадёжного источника, не поленитесь проверить его с помощью этой команды, прежде чем нажать кнопку Открыть. Возможно, такая предосторожность покажется лишней, но она оградит вас от «встречи» с нежелательным контентом.

В большинстве дистрибутивов Linux утилита file (работу которой и запускает одноимённая команда) входит в стандартный набор программного обеспечения.

Синтаксис и опции file

Синтаксис команды file достаточно простой. Записывать её в эмуляторе терминала или консоли следует так:

file опции название_документа

Что же касается опций, то их у этой команды несколько десятков. Мы рассмотрим лишь основные:

  • -b, —brief — запрет на демонстрацию имен и адресов файлов в выводе команды;
  • -i, —mime — определение MIME-типа документа по его заголовку;
  • —mime-type, —mime-encoding — определение конкретного элемента MIME;
  • -f, —files-from — анализ документов, адреса которых указаны в простом текстовом файле;
  • -l, —list — список паттернов и их длина;
  • -s, —special-files — предотвращение проблем, которые могут возникнуть при чтении утилитой специальных файлов;
  • -P — анализ определенной части файла, которая обозначается различными параметрами;
  • -r, —raw — отказ от вывода /ooo вместо непечатных символов;
  • -z — анализ содержимого сжатых документов.

Для того, чтобы ознакомиться с полным списком опций, выполните в терминале команду:

Примеры использования file

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

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

file /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff

Как видно на примере, картинки с расширениями gif и tiff в действительности оказались текстовыми документами, а архив с расширением zip — PDF документом. Кстати, команда file даёт возможность не только проверить, является ли архив архивом, но и заглянуть внутрь, чтобы узнать, что в нём содержится. Для этой цели используется опция -z:

file -z /home/main-user/losst/testarchive.zip

Как вы успели заметить, команда, возвращая ответ, постоянно выводит названия файлов, что в некоторых случаях бывает удобно, но зачастую только усложняет чтение результатов. Отключить эту функцию легко — воспользуйтесь опцией -b:

file -b /home/main-user/losst/test-file.gif /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff

Иногда нужно узнать не просто тип файла, а его MIME-тип. В таком случае на помощь приходит опция -i:

file -i -b /home/main-user/losst/fileA.sbin /home/main-user/losst/fileG.aspx /home/main-user/losst/fileH.lua

Нередко по каким-либо причинам утилита не может найти указанный файл: например, вы ошиблись буквой в его названии или неверно указали папку, в которой он находится. Тогда вывод информации об этом файле предваряет фраза cannot open. Впрочем, есть возможность видоизменить результат, добавив в него сообщение об ошибке. Для этого используйте опцию -E.

Сравните вывод команды с опцией -E и без неё:

file -E -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif

file -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif

Еще один способ работы с утилитой file — запись названий и адресов документов в простой текстовый файл. Применяя этот способ на практике, не забывайте добавлять к команде опцию —files-from, после которой указывайте имя файла, содержащего список документов, и путь к нему.

file —files-from /home/main-user/losst/list_of_files.txt

Выводы

Команда file помогает избежать ситуаций, когда вам приходится открывать подозрительные файлы, не будучи уверенными в их содержимом. Также вы можете использовать её для проверки содержимого нескольких архивов, если есть необходимость найти потерявшийся в большом массиве файлов документ, но нет желания просматривать все архивы вручную.

Источник

Читайте также:  Сбросить кэш днс линукс
Оцените статью
Sr.No. Prefix & Description
1