- 10 different methods to check disk space in Linux
- 1. Check partition size using df command
- 2. Check disk space using fdisk utility
- 3. Check disk space using parted utility
- 4. Check file size using du command
- EG-1: Check size of all the files under a partition recursively
- EG-2: Print total summary of size of files in a partition or directory
- EG-3: Sort the output based on file size
- EG-4: Print file size larger than specified size
- 5. Check disk size using lsblk command
- 6. Print disk size using blockdev
- 7. Check disk size and details using lshw command
- 8. Checking disk size from the system logs
- 9. Check disk size using lsscsi command
- 10. Print disk size using sfdisk
- Summary
- Related Posts
- Проверка диска на ошибки в Linux
- Проверка диска на колоченные секторы в linux с помощью badblocks
- Исправление ошибок файловой системы fsck
- Проверка диска на битые секторы в linux с поддержкою smartmontools
10 different methods to check disk space in Linux
Table of Contents
In this article I will share different commands and methods to check disk space in Linux. Most of these commands and methods should be available on most Linux distros. You can also utilise these commands to create a script to monitor disk size usage and create alarms or send mails (this would need a mail server).
1. Check partition size using df command
df is one of the most used command to check space of available partitions on the Linux setup. You can use df wih -Th to print the partition type and the partition size in human readable format. This command will show you the total available, used and free space per partition.
You can also use other arguments such as -i to print the available, used and free inode count per partition:
You can check the man page of df command for other supported arguments to check disk space in different formats.
2. Check disk space using fdisk utility
fdisk is another very handy utility for system administrators. fdisk is a user interactive program mostly used for creation and manipulation of partition tables such as creating, deleting, modifying partitions. But we can also use this utility to list the available disks connected to the Linux system along with the respective disk size.
Here is a snippet of output from command » fdisk -l »
As you can see from the output, I have a disk /dev/sda with a size of 15GB. The output also shows more details about this disks wherein it contains two partitions /dev/sda1 and /dev/sda2 .
The output of fdisk -l can be quiet long so if you just wish to check the disk space then you can use this command:
Here I have combined fdisk with awk to only print required sections. So I have two disks with 15GB and 8GB each, while I have two LVM partitions which are most likely part of these disks with a size of 14GB and 512MB.
3. Check disk space using parted utility
parted is another alternative to fdisk and is also used for manipulating disk partitions. It is useful for creating space for new operating systems, reorganising disk usage, and copying data to new hard disks.
Similar to fdisk , we can use parted -l to list all the available disks along with their respective size:
If you compare the output of parted with fdisk , here we only get the available disk and their size and the LVM details are missing which is a good thing as we only wanted to check the disk space.
We can also use awk with parted to further only print required output:
4. Check file size using du command
du is another wonderful utility to check the size of files recursively in Linux. It can also summarize disk usage of the set of files, recursively for directories. du is a very versatile tool and supports multiple arguments which you can use based on your requirement. Some of the most used arguments are:
Here are some example demonstrating different scenarios to check file system size using du command:
EG-1: Check size of all the files under a partition recursively
I have a separate partition for /boot :
So let’s check the size of all the files under /boot using du -h /boot/*
EG-2: Print total summary of size of files in a partition or directory
We can use du -c to print a total or summary of all the file size under provided directory or partition.
So the total file size under /etc/iscsi directory is 20K . You can also use this command under root i.e. du -sch /* to get a summary and total size of all the files under /
EG-3: Sort the output based on file size
By default the du command will print the size of the file based on the first available directory or sub-directory. So the output is not sorted and it can be a tedious task to go through the long list. We can combine du with sort command do sort the output based on the file size.
Here we have used du with sort -hr where -h is used to compare human readable numbers such as 2K, 1G, 4M etc while -r is used to reverse the order of search.
EG-4: Print file size larger than specified size
By default du will print the size of every file found under a partition or directory. We can add a threshold to print files higher than a certain size.
For example here we are printing the files with size higher than 1MB under /var/log
For more list of supported options check the man page of du command.
5. Check disk size using lsblk command
lsblk lists information about all available or the specified block devices. The lsblk command reads the sysfs filesystem and udev db to gather information. If the udev db is not available or lsblk is compiled without udev support than it tries to read LABELs, UUIDs and filesystem types from the block device.
We can use lsblk with -o LIST or —output LIST to get desired columns based on the value of LIST. Use lsblk —help to get a list of all supported columns.
We will use name, fstype, size, mountpoint LIST for our example. Although using only size and name was enough but to give more detailed output I am using additional list options.
6. Print disk size using blockdev
We can use blockdev command to print a report for the specified device. It is possible to give multiple devices. If none is given, all devices which appear in /proc/partitions are shown. Note that the partition StartSec is in 512-byte sectors.
You can also use following commands:
7. Check disk size and details using lshw command
lshw is a small tool to extract detailed information on the hardware configuration of the machine. It can report exact memory configuration, firmware version, mainboard configuration, CPU version and speed, cache configuration, bus speed, etc. on DMI-capable x86 or IA-64 systems and on some PowerPC machines.
By default lshw will give you a huge output, we can limit that by only printing the information for a specified class such as » disk «. To get the list of attached disks and their details such as size we will use lshw -c disk .
Here is an output snippet from my Linux node:
We can further improve the output using lshw with grep :
8. Checking disk size from the system logs
We can also use system logs such as boot logs using dmesg or journalctl -b and try to search for respective disk to get more information. The catch is that you should know the disk name unlike other methods which we discussed where we were able to check size of all the available disks without prior knowledge of disk name.
For example, here I am searching for all instance of sda disk in boot logs using dmesg :
Similarly we can search for any other disk, such as sdb :
You may also try grepping blocks in dmesg output which can list the available disk with their size:
9. Check disk size using lsscsi command
lsscsi uses information in sysfs (Linux kernel series 2.6 and later) to list SCSI devices (or hosts) currently attached to the system. Many non-SCSI storage devices (but not all) used the SCSI subsystem in Linux. In lsscsi version 0.30 support was added to list NVMe devices.
We can use lsscsi —size to list all the connected storage devices along with their size as shown below:
10. Print disk size using sfdisk
sfdisk is again an alternative to fdisk and parted utility. One of the major difference between fdisk and sfdisk is that sfdisk reads and writes partition tables, but is not interactive like fdisk or cfdisk (it reads input from a file or stdin). It’s generally used for partitioning drives from scripts or for partition table backup and recovery.
But it can also be used to check the disk size using sfdisk -l , sample output:
Summary
In this article we explored different commands and methods which can be used to check disk size (used/available/total) in Linux. You can easily utilize most of these commands and methods into a script to regularly monitor the available disk space and raise alarm when threshold is reached. There are some more commands such as udisks, hwinfo which can be used to collect similar information but they are distro dependent and may not be available with all the Linux distributions hence I have skipped them.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник
Проверка диска на ошибки в Linux
Когда, при загрузке, операционная система сообщает о наличии ошибок в файловой системе на одном из разделов, то заслуживает незамедлительно сделать в linux проверку диска на ошибки. Любой уважающий себя user не должен забывать, что периодическая проверка жестких дисков на битые сектора и проверка атриторен на ошибки является примером здравого смысла. Для проверки разделов жесткого диска советуем использовать утилиту FSCK (file system consistency check), поскольку утилита FSCK предустановленна на основной массе операционных систем семейства Linux.
Примером хорошего тона и здравого резона является периодическая проверка диска на битые сектора (бэд-сектора, badblocks) и обычная испытание диска на ошибки записи и т.п. Разберёмся что такое битые сектора. Бэд-сектор, Повреждённый сектор — сбойный (не читающийся) или не внушающий доверие сектор диска; кластер, содержащий сбойные сектора, или кластер помеченный таковым в текстурах файловой системы операционной системой. Следовательно, если в битом секторе были этые, то их ещё возможно восстановить, пока битых секторов не стало слишком много для конкретного файла. Собрать список битых секторов можно с помощью команды badblocks.
Проверка диска на колоченные секторы в linux с помощью badblocks
Badblocks — стандартная утилита Linuх для проверки (Тестирование Инвентаризация Допинг-контроль Проверка подлинности Служебная проверка Проверка орфографии Проверка на дорогах Камеральная налоговая проверка Выездная налоговая проверка Проверка) на колоченные секторы. Она устанавливается по-умолчанию практически в любой дистрибутив и с ее помощью можно проверить как твердый диск, так и внешний накопитель. Для начала давайте посмотрим, какие накопители подключены к ушей системе и какие на них имеются разделы. Для этого нам нужна еще одна стандартная утилита Linux — fdisk.
Собрать список битых секторов можно с помощью команды badblocks.
Делается это так:
sudo badblocks -v /dev/hda1 >
Где /dev/hda1 — это разоблачил диска, что вы хотите проверить.
Желательно делать проверку в однопользовательском режиме, когда это не внешний диск. Тогда его просто стоит отмонтировать. После этого мы можем швырнуть утилиту fsck, явно указав ей список битых секторов для того, чтобы она их подметить как «битые» и попыталась восстановить с них данные. Делается это так:
sudo fsck -t ext4 -l
Где ext4 — это тип файловой системы нашего разоблачила диска, а /dev/hda1 — сам раздел диска.
Естественно, что выполнять команды нужно с правами суперпользователя.
Метеопараметром -l мы говорим утилите fdisk, что нам нужно показать список разделов и выйти. Теперь, когда мы знаем, какие разделы у нас есть, мы можем проверить их на битые секторы. Для этого мы станем использовать утилиту badblocks следующим образом:
sudo badblocks -v /dev/sda1 > badsectors.txt
Если же в итоге были найдены битые секторы, то нам надо дать указание операционной системе не вписывать в них информацию в будущем. Для этого нам понадобятся утилиты Linux для работы с файловыми системами:
e2fsck. Когда мы будем исправлять раздел с файловыми система Linux ( ext2,ext3,ext4).
fsck. Если мы станем исправлять файловую систему, отличную от ext.
Исправление ошибок файловой системы fsck
В моей а не твоей статье «Проверка файловой системы на ошибки с помощью fsck на Linux» я расскажу как возможно проверить файловую систему на вашей ОС в Linux. Некоторым системам необходим пароль root дабы запустить fsck или других аналогичных утилит, когда не могут загрузить полностью ОС. В данном случае стоит выполнить проверку диска загрузившись в single-user mode , либо – загрузившись с иного диска. Fsck расшифровывается как «файловая система Проверка целостности» (file system consistency check).
На основной массе систем, Fsck запускается во время загрузки, если определенные условия. Код выхода ворачивается, когда несколько файловых систем которая проверяется побитовое ИЛИ (OR) для каждой файловой системы, какая проверяется. В действительности, Fsck — это просто фронт-энд для различных проверочных утилит для файловых систем (fsck.fstype), какие доступны на Linux. Файловая система (множество элементов, находящихся в отношениях и связях друг с другом, которое образует определённую целостность, единство) для конкретных проверок ищет сначала в /sbin, а потом в /etc/fs и /etc/, и, наконец в директориях, перечисленных в переменной PATH (среда переменного кружения).
Запуск и исполнение FSCK на смонтированной файловой системе может привести к повреждению данных, поэтому применяйте данный материал на свой страх и риск.
Автор не несет ответственности за любой вред, который вы можете причинить. Fsck расшифровывается как «File System ChecK», то есть «испытание файловой системы» и используется для проверки и исправления файловых систем в Linux. В качестве верифицируемой ФС может быть задан раздел (например, /dev/sda1 или /dev/sda8), точка монтирования (/, /home, /usr), или же точна тома или UUID (например, UUID=8868abf6-88c5-4a83-98b8-bfc24057f7bd или LABEL=root).
Как обычно fsck пытается параллельно проверять файловые системы на нескольких разделах для уменьшения времени, нужного для проверки всех файловых систем. Arch Linux при загрузке автоматически будет бросать fsck для проверки систем, если выполняется одно из требований (например, 180 суток работы системы без проверки разделов или 30 монтирований оных). Обычно нет необходимости переопределять проем между проверками.
Для того, чтобы проверить диск в Linux на наличие опечаток файловой системы нам необходимо сначала выяснить имена файловых систем командой:
Дальше нам необходимо размонтировать файловую систему, которую мы будем проверять командой:
И сейчас запускаем утилиту проверки файловой системы и исправления ошибок на ней командой
В том варианте, когда не представляется возможным размонтировать файловую систему, к примеру, когда нужно испробовать корневую файловую систему (/). Перезагрузиться в однопользовательском режиме (команда reboot, и при загрузке необходимо передать ядру параметр single). Перемонтировать корневую файловую систему в режиме «лишь чтение» командой.
mount -о remount rо -t ext3 /
Здесь параметр -о команды mount указывает на присутствие дополнительных опций. Опция remount rо означает перемонтировать в режиме «только чтение». Метеопараметр -t указывает тип файловой системы – ext3, а последний параметр – указывает что это корневая файловая система (/).
И сейчас проверить файловую систему
fsck -y -f -c /dev/hda1
Проверка диска на битые секторы в linux с поддержкою smartmontools
Теперь давайте рассмотрим более современный и надежный способ проверить диск на колоченные секторы linux. Современные накопители ATA/SATA ,SCSI/SAS,SSD имеют встроенную систему самодисциплины S.M.A.R.T (Self-Monitoring, Analysis and Reporting Technology, Технология самоконтроля, анализа и отчетности), которая изготовляет мониторинг параметров накопителя и поможет определить ухудшение параметров работы накопителя на ранешних стадиях. Для работы со S.M.A.R.T в Linux есть утилита smartmontools. Давайте перейдем к работе с утилитой. Включим следующую команду с параметром -H,чтобы утилита показала нам информацию о состоянии накопителя:
sudo smartctl -H /dev/sda1
Как видим, проверка диска («круглое блюдо») — круг (низкий цилиндр) или предмет в виде круга) на битые секторы linux завершена и утилита говорит нам, что с накопителем все в распорядке! Дополнительно, можно указать следующие параметры -a или —all, чтобы получить еще больше информации о накопителе, или -x и —xall, дабы просмотреть информацию в том числе и об остальных параметрах накопителя.
Источник