prevent accidental deletion of files

How to Prevent Accidental File Deletion

It is important to protect the critical files on your system from accidental deletion, otherwise it will be difficult to recover them. You can easily do this using chattr command in Linux. chattr command stands for ‘change attribute’ and prevents files & folders from being deleted or modified in Linux. In this article, we will learn how to prevent accidental file deletion.

How to Prevent Accidental File Deletion

Please note, once you make a file undeletable, using chattr command, even root user will be unable to delete it. Here is the syntax for chattr command.

chattr [operator] [switch] [filename]

In the above command we need to specify the operator (+,-,= operators to add, remove or set file attributes)

Here is a simple command to make file /home/ubuntu/data.txt undeletable.

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

After this, if you try to remove the file using rm command.

$ rm /home/ubuntu/data.txt

you will see the error message.

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

You will also see that the file becomes immutable, meaning you cannot append any data to it.

$ echo 'Hello World!' >> /home/ubuntu/data.txt
bash: /home/ubuntu/data.txt: Operation not permitted

If you want to make the file deletable or modifiable again, use -i option.

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

If you want to make the appendable but not deletable then use +a option.

$ chattr +a /home/ubuntu/data.txt
$ echo 'Hello World!' >> /home/ubuntu/data.txt

If you want to make the file unappendable, use -a switch.

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

If you want to make directories undeletable use -R option. Here is an example to make folder /home/ubuntu undeletable.

$ chattr -R +i /home/ubuntu

Similarly, if you want to make your folder undeletable but appendable, use +a switch with -R option.

$ chattr -R +a /home/ubuntu

On the other hand, if you want to make the folder unappendable, use -a option with -R option.

$ chattr -R -a /home/ubuntu

In this article, we have learnt how to prevent accidental file deletion in Linux using chattr command.

Also read:

How to Make File & Directory Undeletable in Linux
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

Leave a Reply

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