How to Fix Linux rm: Cannot Remove Protected File Error
In this tutorial, you'll learn about How to Fix Linux rm: Cannot Remove Protected File Error. We cover key concepts, practical examples, and best practices.
You run rm and get cannot remove: Permission denied or Operation not permitted — the file is protected by permissions, immutable attributes, or filesystem mount options.
The Problem
rm: cannot remove 'config.ini': Permission denied
Or:
rm: cannot remove 'log.txt': Operation not permitted
Step-by-Step Fix
Step 1: Check file permissions
ls -la config.ini
Expected:
-rw-r--r-- 1 root root 1024 Jun 24 10:00 config.ini
If the file is owned by root, use sudo:
sudo rm config.ini
Step 2: Check immutable attribute
lsattr config.ini
If you see ----i--------- (the i flag), the file is immutable:
# Remove immutable attribute
sudo chattr -i config.ini
# Then remove
sudo rm config.ini
Step 3: Check directory permissions
You need write and execute permission on the directory to delete files:
ls -la /path/to/directory
If you lack write permission on the directory:
sudo chmod +w /path/to/directory
Step 4: Check if the filesystem is read-only
mount | grep " / "
If it shows ro (read-only):
sudo mount -o remount,rw /
Step 5: Check for SELinux or AppArmor
ls -Z config.ini
If SELinux is blocking:
sudo restorecon -v config.ini
Step 6: Remove sticky bit directory protection
In directories with the sticky bit (/tmp), only the file owner can delete:
# Check sticky bit (t at end of permissions)
ls -la / | grep tmp
drwxrwxrwt ... /tmp
Use sudo to override:
sudo rm /tmp/protected-file
Step 7: Use rm -f to force
# -f ignores nonexistent files and never prompts
sudo rm -f config.ini
Prevention Tips
- Use
ls -labefore trying to delete files - Check immutable attributes with
lsattr - Use
ls -la / | grep tmpto check sticky bit directories - Always know what you are deleting —
rm -rfis destructive - Use
trash-cliinstead of rm for recoverable deletes
Common Mistakes with rm protected
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world LINUX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro