Linux File and Directory Attributes

Certain attributes can be set on Linux file and directory helping us control what can and cannot be done on it. Attributes can protect files and directory from being deleted, modified, compressed or updated by any user including root.

The requirement is that your file system is ext3, ext4 or xfs

Common control attributes
a (append) File can only be appended
A Prevents updating the access time
c (compressed) File is automatically compressed on the disk
D Changes on a directory are written synchronously to the disk
e (extend format) File uses extents for mapping the blocks on disk
i (immutable) File cannot be changed, renamed or deleted
S (synchronous) Changes in a file are written synchronously to the disk

There are 2 command that we use to view and administer linux attributes.
lsattr(displays attributes) and chattr(change attributes)

Some basic examples

 
In this example we will add (a) attribute to myfile.txt which will protect this file from being overwritten and only will allow to append

$ lsattr myfile.txt 
-------------e-- myfile.txt
$ echo "some info" > myfile.txt 
$ chattr +a myfile.txt 
chattr: Operation not permitted while setting flags on myfile.txt
$ sudo chattr +a myfile.txt 
$ echo "some info" > myfile.txt 
bash: myfile.txt: Operation not permitted
$ echo "some info" >> myfile.txt 

Here is example of setting immutable (i) attribute to prevent myfile.txt from being deleted or modified.

$sudo chattr +i myfile.txt 
$ lsattr myfile.txt 
----ia-------e-- myfile.txt
$ echo "some info" >> myfile.txt 
bash: myfile.txt: Permission denied

In this example we unset attributes from myfile.txt

$sudo chattr -ia myfile.txt 
$ lsattr myfile.txt 
-------------e-- myfile.txt
$ echo "some info" >> myfile.txt