Celebrate Our 22nd Anniversary with Huge Savings! Up to 70% Off

How to Prevent File/ Directory Modification, Deletion and Renaming in Linux?

To prevent any file from being modified, deleted, or renamed, you will need to set the immutable flag on it, which can be set on files or directories. Once the immutable flag is added, files/folders can't be modified or deleted. 

If you have added an immutable flag and want to make changes in your files, you will need to remove it first; it is an extended file system attribute.

You can refer to the following steps to set the immutable flag, for which you will have to log in with the root to set it.

1. First, we will create a file named test.txt with this command – 

# touch test.txt

2. Use the lsattr command to check the extended attribute.
By default, there is only an 'e' present.

# lsattr test.txt

3. 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

4. Let us use the chattr command to set the +i flag.
Here, i mean immutable.

# sudo chattr +i test.txt

5. Now we will use the command given below to verify the immutable for the test.txt file,

# lsattr test.txt

          Output :

----i---------e---- test.txt

6. As per the above output, test.txt is now immutable.
    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 file cannot be modified or deleted as we have set the immutable flag on it.

Note
If you set immutable to any folder, it will also set the immutable flag for all the files/ folders inside the same folder.

Removing the Immutable

7. 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

8. We will verify that the immutable flag is not removed – 

# lsattr test.txt

Output :

-------------e-- test.txt

Now, you can modify or delete the file without any issues.


Was this answer helpful?

« Back

chat