How to disable delete permission of File and Directory in Linux?

Many times there can be un-intentional delete of files or directories. That can lead to loss of important data or some misconfiguration of the system so we need a way to stop the accidental deletion of files and directories it may not be applicable to all the files and directories but we can have a design where at least some files and directories are prevented from such scenario.

We use the change attribute command to prevent scenario below will see how this command is applied to two files and directories.


Below is the syntax of change attribute command.

chattr [operator] [flag] [filename]
Where the operator can be ‘+’ , ‘-‘ or ‘=’ .
And flag can be set to i to make the file immutable.

Now let’s first investigate the existing attribute of a directory and the files in it. We see that they are normal files which can be rewritten and deleted.

~/Documents/tutorials$ pwd ; ls -l
total 4
drwxrwxr-x 2 ubuntu ubuntu 4096 Dec 31 21:13 linux
~/Documents/tutorials$ lsattr
-------------e-- ./linux
~/Documents/tutorials$ cd linux/
~/Documents/tutorials/linux$ lsattr
-------------e-- ./passwd_bkup.txt
-------------e-- ./movie_list.txt

Now we apply the ‘i’ flag to make one of the file immutable so that it can not be deleted.

$ sudo chattr +i passwd_bkup.txt
[sudo] password for ubuntu:
$ lsattr
----i--------e-- ./passwd_bkup.txt
-------------e-- ./movie_list.txt

As you can see the passwd_bkup.txt file now has i file attribute. Now let’s try deleting this file. The file with I attribute will not get deleted while the other files will get deleted.

$ rm -rf passwd_bkup.txt
rm: cannot remove 'passwd_bkup.txt': Operation not permitted
# Other file gets deleted.
$ rm -rf movie_list.txt
$ lsattr
----i--------e-- ./passwd_bkup.txt

Now the directory containing this file also does not get deleted because it can not become empty.

$ rm -rf linux/
rm: cannot remove 'linux/passwd_bkup.txt': Operation not permitted

Updated on: 03-Jan-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started