chattr

Chattr is a command used to set / unset file attributes in Linux. Usingit 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.

chattr

# chattr +i filename

To prevent anyone - even a root user - from deleting a file, you set the immutable bit of the file using thecommand as follows -

The immutable bit option +i can only be set by the root user. So either you should have root priviledges or you need to use sudo to execute the command.

+i

# chattr -i filename

lsattr

# lsattr filename ----i-------- filename

i

Once thebit is set, even root user won't be able to delete or tamper with the file.To unset the immutable flag -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 thecommand as follows.If the immutable flag is set, there will be anin 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

# chattr +a filename

# chattr -a filename

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:Now the filename can only be opened in append mode for writing data. You can unset the append attribute as follows:To know more aboutcommand, check its man page.