make file and directory undeletable in linux

How to Make File and Directory Undeletable in Linux

Sometimes you may need to make a specific file or directory undeletable in Linux. You can easily do this using chattr command that modifies the attributes of the file/directory making it undeletable. In this article, we will learn how to make file and directory undeletable in Linux.


How to Make File and Directory Undeletable in Linux

Here is a simple example to make /home/ubuntu/data.txt file undeletable or immutable. In this case, the file cannot be modified in any way. It cannot even be renamed or linked to.

You need superuser privileges to set or remove this attribute.

$ sudo chattr +i /home/ubuntu/data.txt
OR
$ sudo chattr +i -V /home/ubuntu/data.txt

You can view the attributes of a file using lsattr command.

$ lsattr /home/ubuntu/data.txt

Now if you try to remove the file, you will get a message that it is not permitted.

$ rm /home/ubuntu/data.txt

rm: cannot remove '/home/ubuntu/data.txt': Operation not permitted
$ sudo rm /home/ubuntu/data.txt
rm: cannot remove '/home/ubuntu/data.txt': Operation not permitted

If you want to make your file deletable again, use -i option in chattr.

$ chattr -i /home/ubuntu/data.txt


How to Make Directory Undeletable

To make directory undeletable, use -R option with chattr command. Here is an example to make /home/ubuntu folder undeletable.

$ sudo chattr +i -RV /home/ubuntu

To make the directory deletable again, use -i option.

$ sudo chattr -i -RV /home/ubuntu

In this article, we have learnt how to make file and directory undeletable in Linux.

Also read:

How to Disable Auto Logout in Linux
How to Make File Unreadable in Linux
How to Measure Elapsed Time in Python
How to Create ISO Image from CD in Linux
How to Export Pandas Dataframe to Multiple Excel Sheets

Leave a Reply

Your email address will not be published. Required fields are marked *