Change read only files in linux

How to make read-only file system writable?

At some point, the filesystem on my digital audio player has become read-only. I cannot copy files into it or remove files on it. Are there some possible reasons for the player’s file system to change permissions in this way? I tried using chmod :

$ sudo chmod a+rw SGTL\ MSCN/ chmod: changing permissions of `SGTL MSCN/': Read-only file system 

Could you also add brand of the player? 🙂 searching ‘SGTL MSN’ actually ONLY brings up this topic 😀 If you are really unlucky it’s the device that’s bugged: as a last(!) resort reset the player. But only when you do not get any good anwsers soon(ish) 🙂

Tried everything, and found a simple solution (heretic). Plug the usb to windows 8 or 7, click «repair external drive», go back to linux. Hope this helps someone.

7 Answers 7

If a filesystem has been mounted read-only, chmod will not work since it’s a write operation too.

Try remounting it read-write:

sudo mount -o remount,rw '/media/SGTL MSCN' 

If the device has a write lock on it (like SD memory cards), you need to turn it off. Hardware locks cannot be disabled by software. Note that the write lock on SD memory cards is located from the sight you see the letters near the up left corner and it looks like a very small switch.

Some filesystem drivers may also not support write operations, this is the case with the older NTFS module supported by Linux. For NTFS filesystems, be sure to use the ntfs-3g driver which should be picked automatically nowadays. If not, you can force the driver with something like:

sudo mount -t ntfs-3g -o uid=$(id -u) /dev/sdb1 /mnt/ 

(where /dev/sdb1 has to be substituted for your block device and /mnt/ for your destination)

@XavierStuvw If read/write protected means readonly, ok. Otherwise you could try to wipe it and repurpose it. The wipefs command can be used on a partition to ensure that no filesystem is recognized. See man wipefs (part of util-linux).

@JoshuaSalazar how did you mount it? Perhaps you could create a new question and include such details, this comment section is getting a bit too large.

For NTFS file systems this problem may occur when it is not properly unmounted (probably by unexpected shutdown of windows). In such cases the file systems are marked as locked.

You can mount them properly using the following ntfsfix command, for example:

Please replace /dev/sda3 with your own device name.

I’d like to add for future Googlers that doing this fixed the «New Steam library folder must be on a filesystem mounted with execute permissions» on Manjaro Linux and it’s probably the same for other distros.

Читайте также:  Arch linux установочные пакеты

Thanks for this! I’m dual booting Kubuntu and Windows 10 and I could not understand why sometimes I’m unable to mount a disk with write permissions!

I had this problem occur on several USB sticks. Each time I searched for an answer and tried various suggestions, including using Terminal to run commands, reformatting on both Linux and Windows machines, etc. All to no avail.

It happened to me again today so again I went looking to see if I could find a solution. I tried the things here, but they didn’t work.

Out of desperation I again went to Disk Utility. I unmounted the drive and then hit «Format» on the partition portion, not the drive portion — USB only had the single partition. This time it WORKED. Then I went to the drive portion and again reformatted the single partition as a master boot drive and monkeyed a bit more with it.

The upshot is, I’m now able to read and write to the drive again.

I don’t know if I just got lucky this time or not. But it is working again.

Источник

How to Overwrite a Read-Only File in Linux

A read-only file implies that the user doesn’t have permission to edit or write. Specifically, the “w” permission would have been disabled for the file. When the file’s property has been set as read-only, the user would neither have permission to write(w) the file nor execute(x) the file and be represented as read-only(r).

Sometimes, it becomes tough for the user to overwrite a read-only file. That’s why we gathered and explained the different methods of overwriting a read-only file in Linux.

How to Overwrite a Read-Only File in Linux?

There are two conditions for overwriting any file – when you are the file owner and when you do not have any ownership access to the file’s properties. Let’s look at the following methods to resolve the issue:

Using the chmod Command

The chmod command is used to modify the properties of a file in Linux, and it has a simple command:

You can alter this permission if you are the file owner by adding the following command:

Let’s take an example where we want to change and overwrite a read-only file located in the Documents directory. Either we can use the directory path in the command or change the current directory of the file:

Note: As you can see in the previous image, we used the -v option or the verbose option to show the resultant changes in the output.

While using this command, it is essential to recollect if you are the only current file user. This command only works if you are a part of the directory in the /etc/sudoers. This step indicates the configuration of the sudo properties of the file using the visudo command.

Читайте также:  Chmod 777 root linux

This command requires a password to gain superuser access to the file. If you want to get the root privileges, please add the “sudo” with the above command:

To give yourself all the permissions related to the file, you can use edit sudoers through the following command:

The following image illustrates that you have the admin privileges as a sudoer, root, and admin access:

admin ALL = ( ALL : ALL ) ALL

If you do not have “ALL” access, please change it accordingly. Now, you have complete access to all the properties related to the file. And you can either read, write or execute the file without encountering any issues.

Conclusion

You can edit and overwrite a read-only file in Linux using multiple commands and sudo privileges. Even if you don’t have the sudo privileges, you can easily access the superuser benefits using sudo by accessing the root directories. We hope this article improved your knowledge of the comprehensiveness of overwriting a read-only file in Linux.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Источник

Исправление Read-Only File System в Linux

date

21.10.2022

user

itpro

directory

CentOS, Linux, Ubuntu

comments

Один комментарий

В некоторый случаях файловая система в Linux может перейти в состояние read-only, при котором вы можете только читать данные с диска, а при попытке записи любых изменение или создании нового файла появдляется ошибка Read-only file system.

Ошибки файловой системы и опция remount-ro

Проверьте параметры монтирования дисков при загрузке Linux. Настройки монтирования файловых систем при загрузке задаются в файле /etc/fstab.

опции понтирования файловой системы в linux fstab при наличии ошибок

Обратите что в fstab есть строка монтирования корневой директории вида:

UUID=aaaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaa / ext4 errors=remount-ro 0 1

Параметр errors=remount-ro означает, что данная директория будет смонтирована в режиме чтения, если на файловой системе устройства обнаружены проблемы. В этом случае нужно выполнить проверку диска с помощью FSCK.

Обычные файловые системы такие как EXT4/BTRFS/XFS можно монтировать как в режиме записи, так и только для чтения (в отличии от файловых систем ISO или SquashFS, которые доступны только для чтения).

В случае обнаружения ошибок на диске вы можете использовать одну из трех опций errors=[continue|remount-ro|panic]

  • continue – игнорировать ошибки,
  • remount-ro – перемонтировать диск в режиме только для чтения
  • panic – остановить загрузку системы

Вы можете вывести соответствие между UUID диска и именем устройства:

В данном примере вы получили, что вашему UUID соответствует устройство /dev/sda3.

blkid вывести uuid и /dev/sdx имя

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

точки монтирования и файловые системы в linux

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

$ sudo fsck –y UUID=aaaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaa

Если вы не можете прямо сейчас выполнить проверку диска, и вы хотите немедленно вывести файловую систему из режима read-only, нужно выполниться команду:

Read-only файловая система в виртуальных машинах

Файловая система раздела Linux на виртуальной машине можете перейти в read-only в случае недоступность системы хранения данных (СХД). Самый простой способ восстановить работу ОС – выполнить сброс виртуальной машины (фактически перезапуск с параметрами по умолчанию).

Может оказаться, что ВМ с Linux вообще не загружается и вам доступна только командная строка initramfs с предупреждениями:

UNEXPECTED INCONSISTENCY: RUN fsck MANUALLY. Fsck exitrd with code 4. The root file system of /dev/sdx requires a manual fsck.

ошибка проверки файловой системы fsck в initramfs

Initramfs это начальная файловая система в оперативной памяти, которая основана на tmpfs, которая содержит утилиты и скрипты, необходимые для работы с дисками, файловыми системами и тд. После запуска initramfs отобразится проблемная ситуация.

Если же ошибок нет – просто вводим exit. Иначе выполняем проверку диска:

Здесь указан том (в данной случае /dev/sda1), для которого требуется выполнить ручную проверку. С помощью следующей команды можно проверить все подключенные файловые системы:

После этого перезагрузите ВМ.

Предыдущая статьяПредыдущая статья Следующая статья Следующая статья

Источник

How to modify a read-only file system in linux?

I also have Windows 10 installed in my system (dual boot) and I want to make some changes in the source code, but I keep getting this error:

chmod: changing permissions of 'filename': Read-only file system 
  • chmod 777 file
  • mount -o remount,rw ‘/myfile/directory’ : which returns no error
  • chown -R root:root /mydir
  • disabling fast boot on Windows (that breaks my OS, I don’t know why)
  • I tried this

And none of them work. It looks like the product locks its own source files (that’s my best guess).

So how can I solve this?

Here is some actual terminal output:

root@qwxp# chmod g+rw current 

chmod: changing permissions of ‘current’: Read-only file system

root@qwxp# mount -o remount,rw /snap/pycharm-professional/current /` 

The mount command has no output, only if I don’t give it a mount point it will return:

mount: /snap/pycharm-professional/271: cannot remount /dev/loop6 read-write, is write-protected.

root@qwxp# chmod g+rw current 

chmod: changing permissions of ‘current’: Read-only file system

root@qwxp# ls -al total 8 drwxrwxrwx 3 root root 4096 Mar 5 05:46 . drwxr-xr-x 13 root root 4096 Mar 5 06:24 .. drwxr-xr-x 11 root root 239 Jan 27 18:52 271 lrwxrwxrwx 1 root root 3 Mar 5 05:11 **current -> 271** -rw-r--r-- 1 root root 0 Mar 5 05:46 hi.txt 

can you add the actual output of the command mount? The line related to the filesystem you’re having problems with. Before and after the remount. Ideally you should add that to the body of the question.

@HosseinKurd install your app from a different source, anywhere but the damn snap. then you can modify it.thats the solution.

1 Answer 1

If you run df -hT /snap/pycharm-professional/current you will probably find that this is a filesystem of type squashfs .

Squashfs filesystems are read only by design and do not have a built in method to modify any part of the filesystem.

This appears to be a snap installed application. It is unclear from your question why you would want to modify part of an application. There is probably an easier way to do what you are attempting, but you haven’t given enough details to determine that.

Источник

Оцените статью
Adblock
detector