Linux chattr Command

Linux 命令大全Linux Command Reference

The Linux chattr command is used to change the attributes of files or directories. These attributes can control the behavior of the file system and provide more advanced file management features.

Common Attributes

Syntax

chattr [选项] [+/-/=属性] 文件或目录

Common Options

  • -R: Recursively process directories and their subdirectories
  • -V: Display detailed information
  • -v: Display version information

Attribute Modes

  • +: Add attribute
  • -: Remove attribute
  • =: Set to specified attributes

Common Attributes

Attribute 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 have hard links created (requires root privileges).
A Does not update the file's last access time (atime)。
c The file is automatically compressed on disk (supported by some file systems).
s Secure deletion: When the file is deleted, its data is zeroed out (unrecoverable).
u After the file is deleted, its contents can still be recovered (contrary tos).
d The file isdumpskipped during backup.

Examples

Add attribute (+):

sudo chattr +i file.txt  # 设置文件为不可变(防删除/修改)
sudo chattr +a /var/log/syslog  # 日志文件只能追加

Remove attribute (-):

sudo chattr -i file.txt  # 取消不可变属性

Reset attribute (=):

sudo chattr =a file.txt  # 移除所有属性,仅保留 `a`

Protect important configuration files:

chattr +i /etc/passwd
chattr +i /etc/shadow

Set 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` 表示不可变

Linux 命令大全Linux Command Reference

Other Extensions