How to Use chattr to Protect Files and Directories from Accidental Deletion
This guide explains the Linux chattr command, showing how to add immutable or append‑only attributes to files and directories, verify the settings, and later remove the protection, with practical examples and command syntax.
The article introduces the chattr command, available on most Linux distributions, which can assign special attributes to files and directories to prevent accidental deletion or modification.
Basic Syntax
The general form is:
$ chattr <operator> <attribute> <filename>Operators: + – add an attribute - – remove an attribute = – set exactly the specified attribute
Key attributes covered: a – allow appending data only i – immutable (no delete or modify)
Protecting a Single File
To make file.txt immutable: $ sudo chattr +i file.txt Check the attribute with: $ lsattr file.txt Attempts to delete or edit the file (e.g., rm file.txt or echo "text" >> file.txt) will fail with “Operation not permitted”.
To remove the protection:
$ sudo chattr -i file.txtProtecting a Directory Recursively
Apply the immutable flag to all files inside dir1: $ sudo chattr -R +i dir1 Now attempts to delete the directory or any contained file are blocked, just like with a single file.
Append‑Only Mode
If you want a file or directory to allow only data appending, use the a attribute.
$ sudo chattr +a file.txt
$ sudo chattr -R +a dir1After setting this, you can append with echo "text" >> file.txt, but you cannot modify existing content or delete the file.
To revert the append‑only flag:
$ sudo chattr -a file.txt
$ sudo chattr -R -a dir1Summary
Using chattr with the i (immutable) and a (append‑only) attributes provides a reliable way to safeguard important files and directories from accidental removal or alteration, and the attributes can be added or removed as needed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
