By default, all files & folders are liable to modification unless the user does not have adequate permissions for it. But if you want to prevent any file from being modified, deleted or even renamed, then you need to change its immutable flag (i flag). In this article, we will learn how to prevent file from being modified in Linux.
Linux Prevent File From Being Modified
Here are the steps to prevent file from being modified.
Let us first create a new file test.txt for testing.
$ touch test.txt
You can use lsattr command to check the extended attribute values. By default, you will only see ‘e’ value in it.
# lsattr test.txt Output: --------------e---- test.txt
Next, we will add some content in this file since it is editable at this point.
# echo This is a test of immutable flag >> test.txt # cat test.txt
Next, we will use chattr (for change attribute) to set the immutable flag (i flag) of the file.
# sudo chattr +i test.txt
Now let us once again look at the file’s extended attributes.
# lsattr test.txt Output : ----i---------e---- test.txt
Now let us try modifying the above file.
# echo test-modification >> test.txt -bash: test.txt: Permission denied
You will get a permission denied message when you try to modify the contents of the file. Next let us try to delete the file using rm command.
# rm -f test.txt rm: cannot remove ‘test.txt’: Operation not permitted
When you try to delete the file, you will get ‘Operation not permitted’ message.
Finally, let us to try to move the file using mv command.
# mv test.txt test2.txt mv: cannot move ‘test.txt’ to ‘test2.txt’: Operation not permitted
Again, you will get ‘Operation not permitted’ message. As you can see, by setting the file’s immutable flag, it has become unmodifiable.
If you want to make it modifiable as before, use the chattr command as before, to remove the immutable flag.
# sudo chattr -i test.txt
Now you can once again verify the file’s extended attributes using lsattr command.
# lsattr test.txt Output : -------------e-- test.txt
Now you should be able to modify or delete the file as before.
In this article, we have learnt how to prevent file from being modified in Linux. This is useful for system administrators who want to prevent unauthorized users, or anyone for that matter, from modifying, renaming or deleting one or more files & folders.
How to Disable Shutdown & Reboot in Linux
How to Convert Files to UTF8 Encoding in Linux
How to Reduce Inode Usage in Linux
How to Use Port Knocking to Secure SSH in Linux
How to Enable & Disable Line Numbers in Vim