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

Sometimes you need to protect important files and directories from accidental deletion in Linux. The chattr command allows you to change file attributes to make files immutable, preventing deletion even with root privileges.

Syntax

chattr [operator] [flag] [filename]

Where:

  • operator: + (add), - (remove), or = (set exactly)
  • flag: i makes the file immutable (cannot be modified or deleted)

Checking Current File Attributes

First, let's examine the current attributes of files in a directory using lsattr ?

$ pwd ; ls -l
/home/ubuntu/Documents/tutorials
total 4
drwxrwxr-x 2 ubuntu ubuntu 4096 Dec 31 21:13 linux

$ lsattr
-------------e-- ./linux

$ cd linux/
$ lsattr
-------------e-- ./passwd_bkup.txt
-------------e-- ./movie_list.txt

The files show normal attributes with only the e flag (extent format).

Making a File Immutable

Apply the i flag to make a file immutable and prevent deletion ?

$ sudo chattr +i passwd_bkup.txt
[sudo] password for ubuntu:

$ lsattr
----i--------e-- ./passwd_bkup.txt
-------------e-- ./movie_list.txt

Notice the i attribute is now set on passwd_bkup.txt.

Testing File Deletion Protection

Try to delete both files to see the protection in action ?

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

# Other file gets deleted normally
$ rm -rf movie_list.txt

$ lsattr
----i--------e-- ./passwd_bkup.txt

The immutable file cannot be deleted, while the regular file is removed successfully.

Directory Protection

The directory containing the immutable file also cannot be deleted ?

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

Removing Immutable Protection

To restore normal deletion permissions, remove the i attribute ?

$ sudo chattr -i passwd_bkup.txt
$ lsattr
-------------e-- ./passwd_bkup.txt

Common Use Cases

  • System configuration files: Protect /etc/passwd, /etc/shadow
  • Log files: Prevent accidental deletion of audit logs
  • Backup files: Ensure critical backups remain intact
  • Application configs: Protect production configuration files

Conclusion

The chattr +i command provides an effective way to prevent accidental file deletion in Linux. Use lsattr to check current attributes and chattr -i to remove protection when needed.

Updated on: 2026-03-15T17:22:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements