Исправление Read-Only File System в Linux
21.10.2022
itpro
CentOS, Linux, Ubuntu
Один комментарий
В некоторый случаях файловая система в Linux может перейти в состояние read-only, при котором вы можете только читать данные с диска, а при попытке записи любых изменение или создании нового файла появдляется ошибка Read-only file system.
Ошибки файловой системы и опция remount-ro
Проверьте параметры монтирования дисков при загрузке Linux. Настройки монтирования файловых систем при загрузке задаются в файле /etc/fstab.

Обратите что в fstab есть строка монтирования корневой директории вида:
Параметр errors=remount-ro означает, что данная директория будет смонтирована в режиме чтения, если на файловой системе устройства обнаружены проблемы. В этом случае нужно выполнить проверку диска с помощью FSCK.
Обычные файловые системы такие как EXT4/BTRFS/XFS можно монтировать как в режиме записи, так и только для чтения (в отличии от файловых систем ISO или SquashFS, которые доступны только для чтения).
- continue – игнорировать ошибки,
- remount-ro – перемонтировать диск в режиме только для чтения
- panic – остановить загрузку системы
Вы можете вывести соответствие между UUID диска и именем устройства:
В данном примере вы получили, что вашему UUID соответствует устройство /dev/sda3.

Также можно имена устройства и точки монтирования с помощью команды:

Т.к. в данном примере ошибки обнаружены в корневой директории которая является точкой монтирования, вы сможете выполнить ее проверку только загрузившись с LiveCD. Для исправления ошибок файловой системы используется команда:
$ sudo fsck –y /dev/sda3
$ sudo fsck –y UUID=aaaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaa
Если вы не можете прямо сейчас выполнить проверку диска, и вы хотите немедленно вывести файловую систему из режима read-only, нужно выполниться команду:
$ sudo mount -o remount,rw /
Read-only файловая система в виртуальных машинах
Файловая система раздела Linux на виртуальной машине можете перейти в read-only в случае недоступность системы хранения данных (СХД). Самый простой способ восстановить работу ОС – выполнить сброс виртуальной машины (фактически перезапуск с параметрами по умолчанию).
Может оказаться, что ВМ с Linux вообще не загружается и вам доступна только командная строка initramfs с предупреждениями:

Initramfs это начальная файловая система в оперативной памяти, которая основана на tmpfs, которая содержит утилиты и скрипты, необходимые для работы с дисками, файловыми системами и тд. После запуска initramfs отобразится проблемная ситуация.
Если же ошибок нет – просто вводим exit. Иначе выполняем проверку диска:
Здесь указан том (в данной случае /dev/sda1), для которого требуется выполнить ручную проверку. С помощью следующей команды можно проверить все подключенные файловые системы:
Исправление ошибки «Файловая система доступна только для чтения» в Linux

Первый способ исправления ошибки «Файловая система доступна только для чтения» в Linux заключается в проверке прав доступа. Иногда пользователь случайно или намерено устанавливает ограничения, которые распространяются и на других юзеров. Для начала предлагаем проверить атрибуты, а затем внести изменения, если это требуется.
- Запустите консоль удобным для вас методом. Для этого можно использовать соответствующий значок в меню приложений или горячую клавишу Ctrl + Alt + T.

- Здесь введите команду ls -l , чтобы просмотреть весь список дисков с подробной информацией, среди которой будет находиться и необходимая нам.

- Изучите атрибуты, которые показаны в первом столбце напротив проблемного диска или раздела. Если имеется один символ -r, значит, система доступна только для чтения. Наличие w означает открытость для чтения и записи.
После активации команды вы будете уведомлены, что все изменения успешно вступили в силу. Следом рекомендуется перезагрузить ПК и можно приступать к тестированию. Если же при использовании команды ls было обнаружено, что для раздела или носителя установлены все требуемые атрибуты, следует перейти другим решениям возникшей проблемы.
Способ 2: Исправление ошибок через GParted
GParted — одна из самых известных утилит для управления дисками в Linux со встроенным графическим интерфейсом. Ее особенность заключается в наличии множества вспомогательных функций, связанных в том числе и с решением различных ошибок носителей.
- Если GParted по умолчанию отсутствует в вашем дистрибутиве, установите ее с помощью команды sudo apt-get install gparted . Подтвердите это действие, введя пароль суперпользователя и одобрив скачивание архивов.

- После этого утилиту проще всего запустить, нажав на соответствующий значок в меню приложений.
Если какие-то неполадки будут найдены и исправлены, вы получите соответствующее уведомление. По окончании проверки следует перезагрузить ПК, чтобы при начале следующего сеанса сразу проверить эффективность выполненных действий. Если они не принесли никакого результата, переходите далее.
Способ 3: Исправление поврежденных блоков
Иногда ошибка со сбойным режимом чтения возникает вследствие повреждения секторов жесткого диска. Существуют специальные утилиты, позволяющие распределить проблемное пространство или исправить его, если это является возможным. В Linux имеется встроенная команда, отвечающая за выполнение этой операции. Мы и предлагаем воспользоваться ей в том случае, если приведенные выше рекомендации не принесли никакого результата.
- Для начала просмотрим список дисков, чтобы понять, какой из них следует проверять. Осуществляется это через команду fdisk -l .

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

- Теперь используйте команду hdparm -i /dev/sda2 | grep Model , чтобы проверить выбранный носитель или логический диск. Здесь замените /dev/sda2 на определенное ранее название.

- После этого следует отмонтировать диск, чтобы в дальнейшем запустить проверку блоков. Осуществляется это через строку umount /dev/sda2 .

- Запустите проверку, вставив команду badblocks -s /dev/sda2 > /root/badblock .

- Обнаруженные блоки, которые не подлежат исправлению, требуется отметить, чтобы система перестала их задействовать. Для этого используйте e2fsck -l /root/badblock /dev/sda2 .

Все изменения будут применены сразу же, однако, как обычно, рекомендуется создать новый сеанс операционной системы, чтобы проверить, была ли решена возникшая неполадка с ошибкой «Файловая система доступна только для чтения».
Способ 4: Форматирование накопителя
Последний метод, о котором мы хотим рассказать в рамках сегодняшней статьи, является самым радикальным, поскольку подразумевает полное форматирование накопителя, после будет восстановлено состояние файловой системы. Такой вариант подойдет только в той ситуации, если на диске нет важных файлов и все содержимое можно удалить. Более детальные инструкции по данной теме ищите в отдельном материале на нашем сайте, воспользовавшись указанной далее ссылкой.
Сегодня мы разобрали четыре метода исправления неполадки «Файловая система доступна только для чтения». Осталось найти подходящий только путем перебора, выполняя по порядку все приведенные инструкции. В большинстве случаев хотя бы один из них оказывается действенным и позволяет полностью устранить рассмотренную ошибку.
How to Fix Read Only File System Error on Ubuntu
The “Read-only file system…” error is a file system-related error. This could happen in many circumstances for various causes. In this article, we will discuss how to fix read only file system error on Ubuntu.
Please enable JavaScript
A filesystem is a grouping of data (files and directories) kept on a storage device in Linux. The filesystem is used by your operating system to report the physical location and positioning of the files. The files would appear as invisible or random bits without the filesystem.
Each file system also has its own permissions, which control which users or groups can read and write files. The “Read-only file system” problem on Ubuntu will be fixed with this guide.
How to Fix Read Only File System Error on Ubuntu
read-only file system for Ubuntu
By default, Ubuntu has a read-only file system. It implies that the user cannot change or remove files from the system. It helps to safeguard system data and folders and stop unintentional removals. Linux distribution Ubuntu uses the read-only ShrinkFS file system.
This file system saves disk space. It can be used to keep executables, configuration files, and other information that shouldn’t be changed by the user. Linux distribution Ubuntu comes included with a read-only file system. The “Btrfs” file system aims to increase performance and dependability.
The read-only file system cannot be removed using rm.
An error warning will appear if you attempt to delete a read-only file system while the machine is running. It is thus because you cannot delete the file system, which is a component of the computer’s main operating system.
A read-only file system cannot be removed, and any attempts to rename or relocate it will fail with a read-only file system error message. It’s because the Rm command cannot alter a read-only file system’s permissions. Use the Remove-Item cmdlet to correctly remove a read-only file system.
Filesystem Access Rights
Linux is an OS that supports multiple users. Linux uses several security mechanisms to regulate which user has access to which area of the system. File permissions and ownership are one such functionality. It establishes the file’s owner and who has access to read, write, and execute the files.
Linux filesystems follow a similar principle. User permissions secure each filesystem by dictating who is permitted to carry out certain actions on the filesystem.
Because the target filesystem is a read-only filesystem, as the error says, it is rejecting write requests. If it’s intentional, you’ll need the system administrator’s written consent if you want to proceed. If that isn’t the case, then adhere to this advice.
Symptom
On a Linux system, the notification Read-only file system appears when you delete or change a file.
Potential Causes
These are some of the potential reasons:
- After that, the file system enters read-only mode.
- The mounted file system is read-only.
- The hardware is broken, for instance, the disk has damaged sectors, or the RAID controller card is broken.
Precautions
- Data loss could occur when file systems are repaired. Back up your files first.
- Check for a hardware defect if your problem doesn’t fit into one of the following categories.
Solution
The filesystem’s permissions need to be fixed to resolve this problem. Several tools are available, depending on the type of filesystem.
These actions are usually best carried out from a live Ubuntu session. No other program will interfere with the process in this manner. As an alternative, you can start Ubuntu from a different installation. With that said, you may want to consider setting up Ubuntu on a USB drive.
Display Mounted File Systems
We shall first list the file systems that are already mounted. The mounted file systems can be listed using the mount command. Even though the output may be lengthy, only look for the lines about the root path and home path.

The third line from the bottom is the line we are interested in when looking at this screenshot.
File System Remount to Fix Read Only Error on Ubuntu
Remounting the file system is the first thing to do when dealing with a read only file system error on Ubuntu. Because the file system might be mounted as read-only for various reasons that happen occasionally.
Remounting the file system will therefore make it mount normally. The following command can be used to remount specific file systems that are listed in the /etc/fstab configuration file. Naturally, root privileges are required for this action.
Re-Mount Read-Write File System
By default, the file system is set up to be mounted as read-only. However, read-write mounts for these file systems are also an option. To mount, read and write, use the rw option.
Target Filesystem
Choose the filesystem you’ll be working with first. Use the following command to list all filesystems that are accessible:

As an alternative, we can list every mounted filesystem using the findmnt tool:

Choose the target partition or device from the list. In this case, /dev/loop17 is my target device.
You can alternatively use the GNOME Disks tool if you want a graphical user interface:

System Reboot to Fix Read Only Error on Ubutu
Rebooting the machine is another method to fix read only file system error on Ubuntu. A system reboot creates a new beginning where previous errors, which may be connected libraries, configuration, temporary changes, etc., are cleared.
![]()
Look For Errors In The File System on Ubuntu
Generally, when a computer reboots, the file system is checked for errors, and any found are corrected. However, this might not always be successful. Using the fsck command, mistakes can be specifically checked and automatically corrected.
Remediating the File System on
The majority of Linux systems (including Ubuntu) provide fsck, a specific utility for repairing a Linux filesystem, after we’ve identified the filesystem and the appropriate time to repair it. Find out more about how to use fsck on Linux.
Run the following command to repair the filesystem:
If you’re using GNOME Disks, choose the filesystem, select “Repair Filesystem” from the drop-down menu, and then click the gear symbol.
Then restart the computer. Now, the filesystem ought to operate as anticipated.
Prevention of File System Error on Ubuntu
Every filesystem is susceptible to error and corruption. To promote general stability, we can cultivate the following habits:
- Before turning off the machine, properly shut down your system. Data damage and numerous file system issues are frequently the results of improper shutdown.
- Be sure to properly eject/unmount any portable storage from the system before removing it. If not, the filesystem might become corrupt (especially FAT-based file systems).
- Keep an eye on the hard drive’s SMART information if you’re working with one. Before your hard disk dies, it may let you know whether the drive is on its last legs.
- Keep a copy of your crucial files on a different drive so you won’t get locked out.
Final Remarks
In this tutorial, we show how to fix a filesystem that prevented write operations and turned Ubuntu into a “Read-only file system.” A few methods to lessen the possibility of filesystem corruption were also covered.
Some filesystems, like ZFS, are more resistant to corruption than others. It can handle large storage capacities and has built-in data integrity protection and data compression. Look into installing ZFS on Ubuntu.
How to fix read-only file-system on 18.04
Today, after several uninterrupted weeks of happily using my Ubuntu machine again, I ran into another error, this time just after okaying a typical software update. Instead of giving me a successful package installation message, it gave me some sort of notification that «the daemon that allows installation is not working». I can’t remember if that was exactly it or not, but I hit «ok» and the box went away. Strange I thought.
Suspecting something was up, I immediately hooked up my external drive to make a backup — but my drive wouldn’t mount. It was visible in Nautilus, but when I clicked on it, it said:
So apparently my file system has up and decided to go read-only. Is there a way to fix this, or must I purchase a new hard drive and start over? Is there a way to somehow mount my external drive and backup my data first? Can this somehow be fixed using fsck , a command I don’t know about?
My system is set up with my / Ubuntu partition on a 250GB SSD, and my /home on a separate 500GB HDD. I believe the problem must be with my / drive, since I can still edit and save anything in my home directory as normal. I seem to be unable to edit anything on the / drive though, like install software or mount drives. Here is a screenshot of the errors I got when trying to make a backup using Aptik: 
I’m still new to computers so am rather clueless here. Any help would be really appreciated.