Sometimes, you need to protect a file from accidental deletion or renaming—especially if it’s a critical config, log, or script. In Linux, there’s no “lock” checkbox like in some desktop environments, but there are effective ways to secure your files using permissions and attributes.
Here’s how to do it.
Method 1: Use chattr
to Make a File Immutable
The simplest and most effective way to lock a file is with the chattr
command, which changes file attributes on ext2/ext3/ext4 filesystems.
To lock a file:
sudo chattr +i filename
This makes the file immutable:
- It can’t be modified.
- It can’t be renamed.
- It can’t be deleted.
- Not even root can do it without reversing the change.
To unlock the file:
sudo chattr -i filename
Method 2: Change File Permissions
Another approach is modifying permissions so others can’t mess with the file—even if they have access to the directory.
Make a file read-only:
chmod 444 filename
This prevents writing, but doesn’t stop deletion if someone has write access to the directory itself.
Lock down the directory:
chmod 500 directory/
This prevents anyone from creating, deleting, or renaming files in that directory—unless they’re root or the owner with permission.
Note: This method is weaker than chattr +i
and can be bypassed more easily.
Bonus: Prevent Changes with ACL (Access Control Lists)
If you’re on a multi-user system and want fine-grained control, use ACLs.
Example: Deny delete access for a user
setfacl -m u:username:rx filename
You can also lock down the parent directory to block deletions:
setfacl -m u:username:--x directory/
Check ACLs with:
getfacl filename
TL;DR
- Best method:
sudo chattr +i file
— file becomes undeletable and unmodifiable. - Good alternative: Use
chmod
to restrict writes, but it won’t stop deletes. - Advanced option: ACLs give you per-user control but require more setup.
Final Tip
Locking a file is powerful—but use it wisely. If you forget it’s immutable, your scripts or software might fail silently when trying to write to it.
Need to automate locking/unlocking? Just wrap the chattr
commands in a script.
Want help setting up file protection for a specific use case or server? Drop a comment or reach out—I’m happy to help.
Leave a Reply