- Команда file в Linux
- Синтаксис и опции file
- Примеры использования file
- Выводы
- 5 Commands to View the Content of a File in Linux Command Line
- 5 commands to view files in Linux
- 1. Cat
- 3. Less
- 4. Head
- 5. Tail
- Bonus: Strings command
- List of Commands to get Linux system info using terminal
- Commands to View Linux System info using terminal
- 1. Check Linux system CPU info and Virtualization support
- 2. Know about Linux System RAM details
- 3. Find out BIOS Info on Linux using Dmidecode
- 4. Command to view hard disk and partition distribution
- 5. Check Network card information
- 6. View PCI Slots information on Linux system
- 6. USB controllers and attached devices
- 7. Command to get complete Linux OS information
- 8. Command to get Linux Kernel Information
- 9. View Real-time processes
- 9. Complete Linux System Hardware Information
Команда 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 помогает избежать ситуаций, когда вам приходится открывать подозрительные файлы, не будучи уверенными в их содержимом. Также вы можете использовать её для проверки содержимого нескольких архивов, если есть необходимость найти потерявшийся в большом массиве файлов документ, но нет желания просматривать все архивы вручную.
Источник
5 Commands to View the Content of a File in Linux Command Line
If you are new to Linux and you are confined to a terminal, you might wonder how to view a file in the command line.
Reading a file in Linux terminal is not the same as opening file in Notepad. Since you are in the command line mode, you should use commands to read file in Linux.
Don’t worry. It’s not at all complicated to display a file in Linux. It’s easy as well essential that you learn how to read files in the line.
Here are five commands that let you view the content of a file in Linux terminal.
5 commands to view files in Linux
Before you how to view a file in Unix like systems, let me clarify that when I am referring to text files here. There are different tools and commands if you want to read binary files.
1. Cat
This is the simplest and perhaps the most popular command to view a file in Linux.
Cat simply prints the content of the file to standard display i.e. your screen. It cannot be simpler than this, can it?
cat displays the content of the file on the screen
Cat becomes a powerful command when used with its options. I recommend reading this detailed tutorial on using cat command.
The problem with cat command is that it displays the text on the screen. Imagine if you use cat command with a file that has 2000 lines. Your entire screen will be flooded with the 200 lines and that’s not the ideal situation.
So, what do you do in such a case? Use less command in Linux (explained later).
The nl command is almost like the cat command. The only difference is that it prepends line numbers while displaying the text in the terminal.
nl command displays text with line numbers
There are a few options with nl command that allows you to control the numbering. You can check its man page for more details.
3. Less
Less command views the file one page at a time. The best thing is that you exit less (by pressing q), there are no lines displayed on the screen. Your terminal remains clean and pristine.
I strongly recommend learning a few options of the Less command so that you can use it more effectively.
There is also more command which was used in olden days but less command has more friendly features. This is why you might come across the humorous term ‘less is more’.
4. Head
Head command is another way of viewing text file but with a slight difference. The head command displays the first 10 lines of a text file by default.
You can change this behavior by using options with head command but the fundamental principle remains the same: head command starts operating from the head (beginning) of the file.
5. Tail
Tail command in Linux is similar and yet opposite to the head command. While head command displays file from the beginning, the tail command displays file from the end.
By default, tail command displays the last 10 lines of a file.
Head and Tail commands can be combined to display selected lines from a file. You can also use tail command to see the changes made to a file in real time.
Bonus: Strings command
Okay! I promised to show only the commands for viewing text file. And this one deals with both text and binary files.
Strings command displays the readable text from a binary file.
No, it doesn’t convert binary files into text files. If the binary file consists of actual readable text, strings command displays those text on your screen. You can use the file command to find the type of a file in Linux.
Conclusion
Some Linux users use Vim to view the text file but I think that’s overkill. My favorite command to open a file in Linux is the less command. It leaves the screen clear and has several options that makes viewing text file a lot easier.
Since you now know ways to view files, maybe you would be interested in knowing how to edit text files in Linux. Cut and Paste are two such commands that you can use for editing text in Linux terminal. You may also read about creating files in Linux command line.
Источник
List of Commands to get Linux system info using terminal
In Linux, we can use the command terminal to check various system hardware configurations and information such as CPU, Memory, hard disk, etc., and here are those to use…
Although there are tools that can display Linux system info graphically, however, here we are going to use the inbuilt commands.
The question of how a system is equipped and how it performs in harsh everyday life is not only of theoretical interest. Lot’s of time to solve a problem we need to know hardware and its utilization to remove some bottleneck. Thus, if you are new to Linux systems or running any cloud server where you want to know about the system load, the network interface, and type of processor and chipset, or what hardware is actually in the system? Then here some top commands to follow…
Commands to View Linux System info using terminal
Here we are using Ubuntu 20.04 to display the results of the Linux system info commands, however, you can use them on older versions such as Ubuntu 18.04/16.04 including RPM-based distros like CentOS and RHEL. Apart from them, others are also supported such as Debian, Linux Mint, Kali, Elementary OS, Manjaro, and more.
1. Check Linux system CPU info and Virtualization support
To check out the full information of Linux system’s CPU such as Type of Architecture (i386, x86_64, etc.) (32-bit or 64-bit), Socket, Cores per socket, CPU speed, L cache, Virtualization type or support, etc. use the below given single command:
Furthermore, you can also check each CPU in detail (CPU model, frequency, etc.) of your computer, laptop, or server using:
Output:
2. Know about Linux System RAM details
Check out free Memory on your Linux system along with details of its size and hardware information.
To print free available RAM, type:
Those who are interested in full detail such as Total Memory, Free Memory, Buffers, Cache, Swap cached, Active, mapped, and more… can go for this one:
To identify each RAM used on each memory slot of your system’s motherboard, print the Memory Controller information using the dmidecode command:
3. Find out BIOS Info on Linux using Dmidecode
Dmidecode dumps the DMI (Desktop Management Interface) information of the machine in a readable way. This information includes hardware and BIOS.
You can get the current configuration and the maximum configuration supported by the system, such as the maximum amount of memory supported that we already have shown above…
Therefore, here are some uses of the dmidecode command to know further details of the system as well such as BIOS version, motherboard, and processor.
If you want to view all Linux useful system information use this one. However, it will give a lot of information.
4. Command to view hard disk and partition distribution
Do you want to know about each size of Hard disk and partition available? Then use-
OutPut:
Furthermore, those who want to dig more on hard disk and partitions, then to have each detail of the installed drives run fdisk -l with sudo rights:
Output
To get a clear view and all information along with the type of file system and partitions mounted points, we can also use:
Mount points can be further elaborated with:
5. Check Network card information
The network card installed on our Linux system is one of the important components to connect the internet and other local networks. However, to know its model, manufacturer, and other information without operating the system’s case, use the below-given commands.
Find out the IP address and available active ethernet interfaces:
Now, after using the above command you get the IP address and active ethernet interface, just use that with the below command. For example, ens33 is our interface.
The ethtool will show all information about the network card bandwidth such as what is the max speed, supported link modes, ports, and more…
To get network information we can also use Net-tools, however, we need to install it because by default it would not available on the system.
For Debian/Ubuntu: sudo ap tinstall net-tools
For RHEL/CentOS/Fedora– sudo yum install net-tools or sudo dnf install net-tools
To know Ipaddress:
For getting details of active connections, protocols, domain sockets, and more…
6. View PCI Slots information on Linux system
PCI slots, where we use graphic cards, network cards, and other third-party hardware directly on the Motherboard. To know about these PCI hardware slots run:
If you want more detailed information: lspci -v or lspci -vv
To see the device tree: lscpi -t
6. USB controllers and attached devices
View the details of USB slots and the devices plugged into them using lsusb command:
To have detailed info on USB slots and their active devices use :
7. Command to get complete Linux OS information
When we are running a Linux server and after upgrading or having installation, in case we want to know what version of Linux operating system we are using then, that is possible as well using the command terminal.
Get release info only:
8. Command to get Linux Kernel Information
A kernel, which is the core part of our Linux system, to check out which version we on before updating or after, run:
9. View Real-time processes
To go a bit further and know PID (Process ID, Unique number of the process) of the process executed on the system along with what is currently active we can use two commands:
To check out the PID (Process ID, Unique number of the process) of the process.
Real-time display of process status
A top is a text-based tool that gives complete information of currently active processes in real-time. To exit it, press Ctrl+C.
9. Complete Linux System Hardware Information
Here is the one final command that can give all the hardware information of your Linux system in a single shot. However, displaying all data in one place may feel clutter but if you don’t want to use multiple commands, then this one is for you.
Those who want to omit the slight unwanted information can use the same command with a short flag.
The good thing, if you want to print or save your Linux system hardware information in HTML format then that is also possible using lshw, simply run:
you will see the created file.
Now, open your browser and type or paste: file:///home/ubuntu/lshw-info.html
Closing thoughts:
So, these were some common commands we can use to find out Linux system info on CPU, Memory, OS, kernel, Network, and more. Although, these are not the only there are so many others, so keep searching this big world of Linux. If you know some commands to get a better view of the Linux system then the comment section is all yours…
Источник