1

I have a script file that is currently in sudoers, and for security I want this file to be read only... so I issued the following chmod:

chmod 555 test.sh

Now the permissions on this file are

-r-xr-xr-x  

However, when I go to vi this file, even though it says W10: Warning: Changing a readonly file, I can still do "w!" to force save it. How can I also disable force saving so that a regular user wont be able to write to this file at all?

  • 1
    Force saving effectively deletes and recreates the file. The user needs write permissions on the parent directory to force save. – jordanm Apr 15 at 21:49
  • So I have a script file that is currently in sudoers What exactly do you mean by that? If you just want users to be able to read the file, I can't see why you'd need sudo for that. And if you don't want users to be able to modify the file, you likely don't want to enable sudo editing of the file. – Andrew Henle Apr 15 at 22:08
1

On Linux systems, set the immutable file attribute with chattr.

sudo chattr +i file

A file with the 'i' attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file, most of the file's metadata can not be modified, and the file can not be opened in write mode. Only the superuser or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.

Use lsattr to list a file's attributes.

lsattr -l myfile
myfile    Immutable

The downside of doing this is that you won't be able to write to the file even as the superuser (root). You will need to remove the immutable attribute first:

sudo chattr -i file

On macOS, the chflags command is used to set and reset the immutable flag. To set:

chflags uchg file

and to unset, or clear:

chflags nouchg file

These operations may be performed by either the owner of a file or the superuser.

With macOS, using the -Ol flags with ls show the immutable flag as uchg when set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.