Linux chattr Command
The Linux chattr command is used to change the attributes of files or directories. These attributes can control filesystem behavior and provide more advanced file management features.
Common Properties
Syntax
chattr [选项] [+/-/=属性] 文件或目录
Common options
-R: Recursively process directories and their subdirectories-V: Display detailed information-v: Display version information
Attribute modes
+: Add an attribute-: Remove an attribute=: Set to the specified attributes
Common Properties
| property | Description |
|---|---|
a |
Append only: The file can only be appended to; existing content cannot be deleted or modified (requires root privileges). |
i |
Immutable: The file cannot be deleted, modified, renamed, or hard-linked (requires root privileges). |
A |
Do not update the file's last access time (atime). |
c |
The file is automatically compressed on disk (supported by some filesystems). |
s |
Secure deletion: when the file is deleted, its data is zeroed out (unrecoverable). |
u |
After a file is deleted, its contents can still be recovered (unlike the s no_grad). |
d |
attribute); files are skipped during dump backup. |
Example
Add an attribute (+):
sudo chattr +i file.txt # 设置文件为不可变(防删除/修改)
sudo chattr +a /var/log/syslog # 日志文件只能追加
Remove an attribute (-):
sudo chattr -i file.txt # 取消不可变属性
Reset attributes (=):
sudo chattr =a file.txt # 移除所有属性,仅保留 `a`
** Protect important configuration files:**
chattr +i /etc/passwd
chattr +i /etc/shadow
Set a log file to append only:
chattr +a /var/log/messages
Recursively set directory attributes:
chattr -R +i /etc/important/
View file attributes (using the lsattr command):
lsattr filename
Example output:
----i--------- file.txt # `i` means immutable
Linux Command Reference