Ошибка no space left on device в Linux
Ошибка no space left on device в Linux может возникать при использовании различных программ или сервисов. В графических программах данная ошибка может выводится во всплывающем сообщении, а для сервисов она обычно появляется в логах. Во всех случаях она означает одно. На разделе диска, куда программа собирается писать свои данные закончилось свободное место.
Избежать такой проблемы можно ещё на этапе планирования установки системы. Выделяйте под каталог /home отдельный раздел диска, тогда если вы займете всю память своими файлами, это не помешает работе системы. Также выделяйте больше 20 гигабайт под корневой раздел чтобы всем программам точно хватило места. Но что делать если такая проблема уже случилась? Давайте рассмотрим как освободить место на диске с Linux.
Как исправить no space left on device
Первым дело надо понять на каком разделе у вас закончилась память. Для этого можно воспользоваться утилитой df. Она поставляется вместе с системой, поэтому никаких проблем с её запуском быть не должно:
На точки монтирования, начинающиеся со слова snap внимания можно не обращать. Команда отображает общее количество места на диске, занятое и доступное место, а также процент занятого места. В данном случае 100% занято для корневого раздела — /dev/sda5. Конечно, надо разобраться какая программа или файл заняла всё место и устранить эту проблему, но сначала надо вернуть систему в рабочее состояние. Для этого надо освободить немного места. Рассмотрим что можно сделать чтобы экстренно освободить немного памяти.
1. Отключить зарезервированное место для root
Обычно, у всех файловых систем семейства Ext, которые принято использовать чаще всего как для корневого, так и для домашнего раздела используется резервирование 5% памяти для пользователя root на случай если на диске закончится место. Вы можете эту память освободить и использовать. Для этого выполните:
sudo tune2fs -m 0 /dev/sda5
Здесь опция -m указывает процент зарезервированного места, а /dev/sda5 — это ваш диск, который надо настроить. После этого места должно стать больше.
2. Очистить кэш пакетного менеджера
Обычно, пакетный менеджер, будь то apt или yum хранит кэш пакетов, репозиториев и другие временные файлы на диске. Они некоторые из них ненужны, а некоторые нужны, но их можно скачать при необходимости. Если вам срочно надо дисковое пространство этот кэш можно почистить. Для очистки кэша apt выполните:
sudo apt clean
sudo apt autoclean
Для очистки кэша yum используйте команды:
3. Очистить кэш файловой системы
Вы могли удалить некоторые большие файлы, но память после этого так и не освободилась. Эта проблема актуальна для серверов, которые работают долгое время без перезагрузки. Чтобы полностью освободить память надо перезагрузить сервер. Просто перезагрузите его и места на диске станет больше.
4. Найти большие файлы
После выполнения всех перечисленных выше рекомендаций, у вас уже должно быть достаточно свободного места для установки специальных утилит очистки системы. Для начала вы можете попытаться найти самые большие файлы и если они не нужны — удалить их. Возможно какая-либо программа создала огромный лог файл, который занял всю память. Чтобы узнать что занимает место на диске Linux можно использовать утилиту ncdu:
sudo apt install ncdu
Она сканирует все файлы и отображает их по размеру:
Более подробно про поиск больших файлов читайте в отдельной статье.
5. Найти дубликаты файлов
С помощью утилиты BleachBit вы можете найти и удалить дубликаты файлов. Это тоже поможет сэкономить пространство на диске.
6. Удалите старые ядра
Ядро Linux довольно часто обновляется старые ядра остаются в каталоге /boot и занимают место. Если вы выделили под этот каталог отдельный раздел, то скоро это может стать проблемой и вы получите ошибку при обновлении, поскольку программа просто не сможет записать в этот каталог новое ядро. Решение простое — удалить старые версии ядер, которые больше не нужны.
Выводы
Теперь вы знаете почему возникает ошибка No space left on device, как её предотвратить и как исправить если с вами это уже произошло. Освободить место на диске с Linux не так уж сложно, но надо понять в чём была причина того, что всё место занято и исправить её, ведь на следующий раз не всё эти методы смогут помочь.
How to Fix the ‘No Space Left on Device’ Error on Linux
So your Linux system is telling you that you have no space left on your hard drive, but you know there is actually a lot of free space left. Why? This is one of those few frustratingly vague errors on Linux systems, but there are a few usual culprits.
Check du and df
Before you go any further, it’s a good idea to check that there really is space left on the disk. While the tools in your desktop environment are good, it’s much better to use the direct ones from the command line.
Begin with du . Point it to the base directory on the drive that’s having the problem. This guide is assuming it’s the partition with root.
It’ll take some time to go through everything. Now, try with df .
Add root and the filesystems mounted under it. For example, if you have “/home” on a separate drive, add that in with the reading for root. The total should come out close to what you had with du . If not, that might point toward a deleted file being used by a process.
Of course, the main concern here is whether or not the results of these commands come in under the size of the drive. If it did, there’s obviously something wrong.
Possible Causes
There are a couple of main causes here. If you saw a discrepancy between du and df you can jump down to the first option here. Otherwise, start at the second one.
Deleted File Reserved by Process
Occasionally, a file will be deleted, but a process is still using it. Linux won’t release the storage associated with the file while the process is still running. You just need to find the process and restart it.
Try to locate the process.
The problematic process should be listed, then just restart it.
Not Enough Inodes
There is a set of metadata on filesystems called “inodes.” Inodes track information about files. A lot of filesystems have a fixed amount of inodes, so it’s very possible to fill the max allocation of inodes without filling the filesystem itself. You can use df to check.
Compare the inodes used with the total inodes. If there’s no more available, unfortunately, you can’t get more. Delete some useless or out-of-date files to clear up inodes.
Bad Blocks
The last common problem is bad filesystem blocks. Filesystems get corrupt and hard drives die. Your operating system will most likely see those blocks as usable unless they’re otherwise marked. The best way to find and mark those blocks is by using fsck with the -cc flag. Remember that you can’t use fsck from the same filesystem that you’re testing. You’ll probably need to use a live CD.
Obviously, replace the drive location with the drive that you want to check. Also, keep in mind that this will probably take a long time.
Hopefully, one of these solutions solved your problem. This issue isn’t exactly easy to diagnose in every instance. With any luck, though, you can get it cleared up and have your hard drive working again as normal.
If you’re looking for more Linux pointers, see our guide on how to set up Bluetooth in Linux. Or, for something a little different, see how to install Mac’s Safari browser in Linux. Enjoy!
Nick is a freelance tech. journalist, Linux enthusiast, and a long time PC gamer.
6 comments
There are more cases where this can happen, e.g. sparse files. Take a look here if you are interested:
This helped me to solve a NetApp disk space mystery.
I’ve never had any of those things above affect my system but I have had, on several occasions, my root drive filled up due to a mounting error. Sometimes my NFS share from my server would be mounted onto root and take up the whole space. I have it exclusively setup in /etc/fstab to mount to /srv/ but randomly this still happens today. Usually I can unmount the NFS share and delete the files that wrote to the /srv and remounted it as a Share but it has been severe enough where I had to restart and boot to single user mode to fix what is going on. What do you think could help fix this problem u have been having? By the way keep up the good work.
Some quite useful tips here, but in all cases, you do not need to use ‘ sudo ‘ with ‘ df ‘.
On ext4 / ext3 filesystems, you might as a last resort do ‘ tune2fs -m1 /dev/sdXX ‘ to decrease the reserved space.
Trying to put a >4GB file on a FAT partition will also give “No space left on device”
I wanted to add what worked for me.
The issue on my case was on a ZFS partition. And it’s apparently a know issue on ZFS that you need empty space to delete a file. After looking around, I found a solution that worked for me. In my case, I couldn’t empty my trash (too full).
find /data/.Trash-1000/ -type f -exec truncate -s 0 <> +
Thanks for this ran all the checks. Cause was a performance hit due to thousands of files and directories on the the cheap low power NAS on an SMB mount. Moved the offending files to another directory problems solved!
Comments are closed.
Popular Posts
Xfce Review: A Lean, Mean Linux Machine
How to Copy and Paste Text, Files and Folders in Linux Terminal
How to Fix High CPU Usage in Linux
Pantheon Desktop Review: A Beautiful Alternative to macOS
How to Verify Checksums in Linux
Ubuntu vs. Linux Mint: Which One Should You Use?
GNOME Shell Review: Minimal Desktop with Great Performance
Which Ubuntu Flavor Should You Choose?
How to Hide Desktop Icons in Ubuntu 20.04
How to Move from Windows to Linux
Affiliate Disclosure: Make Tech Easier may earn commission on products purchased through our links, which supports the work we do for our readers.