In Linux, you can prevent a file or directory from being modified, deleted, or renamed by setting the immutable flag on it. This flag is an extended attribute provided by the Linux file system and is especially useful when you want to secure critical files or directories from unauthorized or accidental changes.
Once the immutable flag is set, the file or folder becomes locked — it cannot be edited, deleted, or renamed even by the root user unless the flag is removed.
You can refer to the following steps to set the immutable flag, for which you will have to log in as the root to set it.
Step 1: Create a Test File
First, we will create a file named test.txt with this command:
# touch test.txt

Step 2: Check Current Attributes of the File
Use the lsattr command to check the extended attribute. By default, there is only an 'e' present.
# lsattr test.txt

Step 3: Add Content to the File
We will add some content to the test.txt, which should work fine as we haven't made any changes yet.
# echo This is a test of immutable flage >> test.txt # cat test.txt

Step 4: Set the Immutable Flag
Let us use the chattr command to set the +i flag. Here, I mean immutable.
# sudo chattr +i test.txt

Step 5: Verify the Immutable Flag
Now we will use the command given below to verify the immutability of the test.txt file:
# lsattr test.txt

As per the above output, test.txt is now immutable.
Step 6: Test File Modification, Deletion, and Renaming
We will try to modify or delete the same file.
# echo test-modification >> test.txt

-bash: test.txt: Permission denied
# rm -f test.txt

rm: cannot remove 'test.txt': Operation not permitted
# mv test.txt test2.txt

mv: cannot move 'test.txt' to 'test2.txt': Operation not permitted
As per the above error, we can see that the file cannot be modified or deleted as we have set the immutable flag on it.
Important Note: If you set immutable to any folder, it will also set the immutable flag for all the files/ folders inside the same folder.
Step 7: Remove the Immutable Flag
You must remove the immutable if you want to change the same file. The following command will remove the immutable flag from the files:
# chattr -i test.txt

Step 8: Confirm the Flag is Removed
We will verify that the immutable flag is not removed:
# lsattr test.txt

Once you remove the immutable fag then you can modify or delete the file without any issues.
Conclusion:
By using the chattr +i command, you can effectively lock down critical files and directories in Linux to prevent accidental or unauthorized modifications. This adds a strong layer of security and stability to system configurations, scripts, logs, or application files.
