Chattr is a command used to set / unset file attributes in Linux. Using chattr it is possible to make a file immutable. That is, even a root user will be prohibited from deleting the file.
The trick lies in setting the appropriate attribute for the file.
chattr command is similar to the attrib command in DOS but much more powerful and flexible.
To prevent anyone – even a root user – from deleting a file, you set the immutable bit of the file using the chattr command as follows –
# chattr +i filename
The immutable bit option +i can only be set by the root user. So either you should have root privileges or you need to use sudo to execute the command.
Once the +i bit is set, even root user won’t be able to delete or tamper with the file.
To unset the immutable flag –
# chattr -i filename
Every file in Linux have a number of attributes associated with it. The immutable bit attribute being just one of them. To see what all attributes are set for a particular file, you run the lsattr command as follows.
# lsattr filename ----i-------- filename
If the immutable flag is set, there will be an i in the listing.
The chattr command is used by system administrators to restrict the users from changing a file in a particular way or even the administrator can by mistake delete a critical file because of a mis-typed command. But if the immutable flag is set, these mistakes can be avoided.
chattr can be used to set/unset many more file attributes.
For example, if you want to allow everybody to just append data to a file and not change already entered data, you can set the append bit as follows:
# chattr +a filename
Now the filename can only be opened in append mode for writing data. You can unset the append attribute as follows:
# chattr -a filename
To know more about chattr command, check its man page.