How to Lock a File for Renaming/Deleting in Linux
13:14, 08.07.2026
Do you need to protect important files from accidental delete? Linux provides multiple ways to secure a file and protect it from unintended modifications. Linux offers several methods to lock a file and prevent unwanted changes. Whether you’re securing critical system files or just keeping your work safe, these techniques will help.
Method 1: Prevent File Deletion with chattr
The chattr (change attribute) command allows you to make a file immutable, meaning it cannot be modified, deleted, or renamed.
Follow these steps:
- Open a terminal
- Use the following command to make the file immutable:
sudo chattr +i filename - To verify the attribute, run:
lsattr filename - If you need to modify or delete the file later, remove the immutable attribute:
sudo chattr -i filename
This method is useful for system configuration files or sensitive documents.
Method 2: Restrict Deletion Using File Permissions
Linux file permissions control who can read, write, and execute files. By modifying permissions, you can prevent deletion or renaming.
Your steps:
- Remove write permissions for all users except the owner:
chmod 444 filename
This makes the file read-only
- To prevent others from modifying the file, you can set stricter permissions:
chmod 400 filenam - If needed, restore permissions with:
chmod 644 filename
This approach works well when multiple users share a system.
Method 3: Protect Files by Changing Ownership with chown
Changing the file owner to root or another privileged user can prevent unauthorized modifications.
Your next steps here:
- Change file ownership to root:
sudo chown root:root filename - Combine this with restricted permissions:
sudo chmod 400 filename - If you need to regain ownership, run:
sudo chown yourusername:yourgroup filename
This method is ideal for securing configuration files and preventing accidental changes.
Conclusion
Locking a file in Linux is straightforward. You can make a file immutable with chattr, restrict write permissions with chmod, or change ownership with chown. Each method has its own use case, so choose the one that fits your needs best. By applying these techniques, you can safeguard important files from accidental deletion or modification.