Lock a file on Linux

Here is how to lock a file from write/delete in a dirty way .
this trick will work this file system ext2-4 XFS, ReiserFS, JFS and OCFS2.
and the trick is to use the command chattr for changing file extended attribute .
A file with the ‘i’ attribute cannot be modified: it cannot be deleted or renamed,
no link can be created to this file and no data can be written to the file.
Only the superuser or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.

# echo "Test chattr" >/tmp/test.txt
# touch /tmp/test.txt
# lsattr /tmp/test.txt
--------------e---- /tmp/test.txt
# chattr +i /tmp/test.txt
# lsattr /tmp/test.txt
----i---------e---- /tmp/test.txt
# touch /tmp/test.txt
touch: cannot touch '/tmp/test.txt': Permission denied
Posted in Tips and Tricks Tagged with: ,