Howto: Linux Write protect a file

by on June 12, 2007 · 4 comments· LAST UPDATED May 3, 2008

in , ,

Q. How do I write protect a file under Linux? I’m using CentOS 5 server Linux operating system. I need prevent accidental changes to my files.

A. There are two ways to write protect a file under Linux.

Method #1: You can make file readonly by removing users’ write permission for a file. Under Linux and UNIX user cannot remove or modify file if they don’t have a write permission. You can use normal chmod command for this purpose.

Method #2 : You need to use chattr command which changes the file attributes on a Linux second extended (ext2 / ext3) file system. You need to setup i attribute. A file with the i attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file and no data can be written to the file. Only the superuser (root) or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.

Write protecting a file using chmod command

Let say you want to write protect the file called data.txt so that no other users can change it, enter:
$ chmod go-w data.txt
To provide back permission use:
$ chmod go+w data.txt

Write protecting a file using chattr command

Let say you want to write protect the file called data.txt so that no other users can change it including root user, enter (you must login as the root user to use chattr command):
# chattr +i data.txt
To remove i attribute, enter:
# chattr -i data.txt

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 4 comments… read them below or add one }

1 Esteban May 3, 2008 at 12:13 pm

incorrect syntax

# chattar +i data.txt
To remove i attribute, enter:

this is the correct:

# chattr +i data.txt
To remove i attribute, enter:

Reply

2 nixCraft May 3, 2008 at 12:19 pm

The faq has been updated. Thanks for pointing out typo

Reply

3 luke June 26, 2014 at 9:03 am

you can still do operations like `mv` on the file depending on the directorys permissions in which the file resides. it would be important to consider this too.

Reply

4 vijay October 31, 2014 at 10:17 am

how to remove write protected file

Reply

Leave a Comment

Tagged as: , , , , , , , ,

Previous Faq:

Next Faq: