How to make an immutable file


As we already know, files have access right matrix (read more in this article: “File and directory permissions in Linux / FreeBSD / MasOS“). But that’s not all. There are more mechanisms for accessing files.

For example, we can change file’s attributes. One of them is immutability attribute. Users with high capabilities can set / reset the attribute.

Make a file or folder immutable to changes and deletion, even by superuser (without changing attribute):

chattr +i /path/to/file

Make a file or folder mutable:

chattr -i /path/to/file

Recursively make an entire folder and contents immutable:

chattr +i -R /path/to/directory

For example:

$ touch 1.txt
$ sudo chattr +i 1.txt
[sudo] password for user:
$ rm 1.txt
rm: cannot remove '1.txt': Operation not permitted
$ echo Hello >> 1.txt
-bash: 1.txt: Operation not permitted
$ chattr -i 1.txt  
chattr: Operation not permitted while setting flags on 1.txt
$ sudo chattr -i 1.txt
$ echo Hello >> 1.txt
$ rm 1.txt