Today, we have another simple article, where we discuss how to prevent a file from being deleted. It’s not quite true and I’ll explain in a moment, but for the most part, it makes it so you can’t remove a file by accident or the like. So, if you want to prevent a file from being deleted* read on.
Now, let me be more clear. I’m a bit sorry for the cheesy headline, but there’s a reasonable character limit. I included an asterisk just to make sure. A user with root permissions (eg a user with sudo privileges) can still delete the file – but it takes an extra step to do so. They have to know and work at it to delete the file.
The tool we’re going to use is called chattr. While it looks like ‘chatter’ and I want to type ‘chatter’ every time I use it, it is a tool that you use to change a file’s attributes. It’s a handy tool but we’ll only be examining one specific use for chatter. If you’re curious, the man page defines chatter as:
chattr – change file attributes on a Linux file system
If you’re using a mainstream distro, you shouldn’t need to install chattr. You should find it already installed. Some of the more lightweight distros may not include it by default, but you can verify that it’s installed by running the following in your terminal:
If you do find that chattr isn’t installed, go ahead and install it. It’s in your default repos. I’m sure of it!
Prevent A File From Being Deleted:
You guessed it. You’ll need an open terminal for this one. That’s easy, just press
Now, I’m going to show you how to use chattr to set an immutable bit. It’s not difficult and just uses the +i flag. Let’s start with creating a file:
With the file created, let’s set the immutable bit with chattr:
sudo chattr +i foo.txt
Now, let’s try to remove it with the rm command:
No luck? Well, let’s grab a hammer. We’ll try to remove the file with sudo:
sudo rm foo.txt
Surprise! You still can’t delete it, even with sudo or logging in as root. To delete the file, you have to first remove the immutable bit, like so:
sudo chattr -i foo.txt
After that, you can happily (and trivially) remove the file with:
In case that’s not very clear, I’ve made you an image. That should help!
That should explain it well enough. The file can still be deleted, it just requires sudo and removing the immutable bit from the file’s attributes. Pretty neat, huh?
Of course, there’s always a way for a root user to be able to remove a file. However, you can make it difficult should you want to prevent a file from being deleted. A skilled user will check the file’s attributes and know how to delete the file, so it’s more about protecting a file from being deleted unless you want to.
Thanks for reading! If you want to help, or if the site has helped you, you can donate, register to help, write an article, or buy inexpensive hosting to start your site. If you scroll down, you can sign up for the newsletter, vote for the article, and comment.