DEV Community

Cover image for File Attributes (chattr, lsattr)
Aryan Vaishnani
Aryan Vaishnani

Posted on

File Attributes (chattr, lsattr)

Linux has permissions (rwx) and also file attributes.

Attributes give extra control like:

  1. Prevent delete
  2. Prevent rename
  3. Append only logs

Main commands:

  1. chattr = change attribute
  2. lsattr = list attribute

What is the difference?

Permissions:

rwx

control:

  • read
  • write
  • execute

Attributes control:

  • can delete?
  • can rename?
  • append only?

Extra protection.

1. lsattr

Shows file attributes.

Example:

lsattr file.txt

Output:

  • ---i--------- file.txt

Here:

i

means immutable.

Check folder

lsattr /var/log

2. chattr

Used to add/remove attributes.

Syntax:

sudo chattr +attribute file

Remove:

sudo chattr -attribute file

Important Attributes

Attribute Meaning
i immutable
a append only
d ignore in backup (some tools)
  1. Immutable (i)

Most common.

File cannot:

  • edit
  • delete
  • rename

even by root until removed.

Set immutable

sudo chattr +i file.txt

Check:

lsattr file.txt

Output:

  • ---i--------- file.txt

Try delete

rm file.txt

Fails.

Remove immutable

sudo chattr -i file.txt

Now editable again.

Real Example

Protect config file:

sudo chattr +i /etc/hosts

Prevents accidental changes.

3. Append Only (a)

Allows:

  • add data

Blocks:

  • delete
  • replace old content

Useful for logs.

Set append only

sudo chattr +a app.log

Append works:

echo "error" >> app.log

Overwrite fails:

echo "new" > app.log

Remove

sudo chattr -a app.log

Check attributes on many files

lsattr *

Real-World Usage

Protect important config

sudo chattr +i /etc/resolv.conf

Protect logs

sudo chattr +a /var/log/app.log

DevOps shared server

Prevent accidental delete:

sudo chattr +i deploy.sh

Important Notes

  • mostly works on Linux filesystems like ext4
  • needs sudo/root
  • be careful with +i

Example:

sudo chattr +i /etc/passwd

can block changes until removed

Easy Memory Trick

  • lsattr = list attributes
  • chattr = change attributes
  • +i = lock file
  • +a = only add data

Top comments (0)