How to make undeletable files and directories in Linux
Written by A.Jesin Tuesday, 12 July 2011 04:56
A very useful Linux tip on how to make files and directories undeletable even by the root user. You can apply this tip on all important configuration files so that no one accidentally or intentionally deletes it. To achieve this the chattr (Change Attribute) command is used it Linux. The chattr command “immunizes” the file not only from deletion but also modification. The chattr command does care about chmod values, even if a file has 777 permissions immunizing the file will prevent it from being deleted or modified.
chattr +i /path/to/filename
The above command will add the “immutable” flag to the file. Try removing the file with the rm command and you’ll receive the error
rm: cannot remove `file’: Operation not permitted
The same will happen when you try to modify this file. You can also add the immutable flag to directories.
chattr +i /path/to/directory
This will make the directory undeletable, you cannot create new files inside this directory but existing files can be modified but CANNOT be deleted. To recursively immunize everything inside a directory.
chattr -R +i /path/to/directory
How to remove the immutable flag ?
If you ever what to delete the file the immutable attribute should be removed. For this just use a minus (-) symbol in the place of plus (+)
chattr -i /path/to/file
You can do the same for directories too.
How to view file attributes ?
To find out the attributes of a file included whether the file is immunized
lsattr /path/to/directory
The lsattr will produce an output similar to the one below
----i------------e- ./file
----i------------e- ./dir
-----------------e- ./file2
The letter ‘i’ shows that a file has the immutable attribute. The letter ‘e’ according to the man page of chattr says
The ‘e’ attribute indicates that the file is using extents for mapping the blocks on disk. It may not be removed using chattr(1).
Also read:
- Command to Display Directory Sizes in Linux
- Change Home Directory in Linux
- Mount an ISO file in Linux
- Using custom php.ini files on shared hosting
- Setup Linux DNS Server for Windows Active Directory

Thanks !