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