≡ Menu

chattr command

Q. I'm getting following error on my Debian Linux system:

mv cannot move /etc/resolv.conf.dhclient-new to /etc/resolv.conf: Operation not permitted

How do I fix this problem?
[click to continue…]

Howto: Linux Write protect a file

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

Q. How do I write protect file under Linux so that no one can modify it?

A. You need to use chattr command, which changes the file attributes on a Linux second extended file system. The chattr command supports various attributes.

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 or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute in other words you make a file unchangeable or unalterable.

For example if you want file /data/financial.txt unchangeable by anyone on your system, type the following command (login as the root user):
# chattr +i /data/financial.txt
Now no one can delete or modify file /data/financial.txt. To reset back permission, type the following command:
# chattr -i /data/financial.txt
Use lsattr command to lists the file attributes on a second extended file system. It is use to see attributes set by chattr command.
# lsattr financial.txt
Output:

----i------------ financial.txt

See also: