chattr - Linux


Overview

The chattr command in Linux is used to modify the attributes of files and directories on file systems that support extended attributes, such as ext3 and ext4. It allows administrators to set or clear specific attributes that control the behavior of files and improve data integrity and security.

Syntax

The basic syntax of the chattr command is as follows:

chattr [options] [operator][attributes] files...
  • options: Modifiers that control the overall behavior of the command.
  • operator: Can be + (add attribute), - (remove attribute), or = (set attributes exactly).
  • attributes: One or more attributes to be modified.
  • files: One or more files or directories to apply the attributes.

Options/Flags

  • -V: Verbose mode; reports the details of what the command is doing.
  • -v version: Set the version/generation number of the file.
  • -R: Recursively change attributes of directories and their contents.
  • -a: Set the append-only attribute, preventing files from being deleted or modified but still allowing appends.
  • -i: Make a file immutable, which stops it from being modified, deleted, or renamed.
  • -S: Enable synchronous updates, similar to using the sync mount option.
  • -D: List directories without altering their attributes.

Examples

  1. Making a File Immutable:

    chattr +i filename.txt
    

    This example sets the immutable attribute on filename.txt, preventing it from being modified.

  2. Recursively Adding Append-Only Attribute to All Files in a Directory:

    chattr -R +a /path/to/directory
    

    This will apply the append-only attribute to all files within the specified directory and its subdirectories.

  3. Removing the Immutable Attribute:

    chattr -i filename.txt
    

    This command clears the immutable attribute from filename.txt, allowing standard file operations.

Common Issues

  • Filesystem Support: chattr might not work on all filesystems; it primarily supports ext2, ext3, and ext4.
  • Permission Denied: You need to have sufficient permissions (typically root) to modify attributes.

Integration

Combine chattr with other commands for powerful effects:

find /secure-directory -type f -exec chattr +i {} \;

This command finds all files in /secure-directory and makes them immutable.

  • lsattr: Display file attributes set by chattr.
  • stat: Show file or file system status.

For more information, consult the chattr man page by running man chattr in your terminal.