≡ Menu

Howto: Linux Write protect a file

Q. How do I write protect a file under Linux? I’m using CentOS 5 server Linux operating system. I need prevent accidental changes to my files.

A. There are two ways to write protect a file under Linux.

Method #1: You can make file readonly by removing users’ write permission for a file. Under Linux and UNIX user cannot remove or modify file if they don’t have a write permission. You can use normal chmod command for this purpose.

Method #2 : You need to use chattr command which changes the file attributes on a Linux second extended (ext2 / ext3) file system. You need to setup i attribute. A file with the i attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file and no data can be written to the file. Only the superuser (root) or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.

Write protecting a file using chmod command

Let say you want to write protect the file called data.txt so that no other users can change it, enter:
$ chmod go-w data.txt
To provide back permission use:
$ chmod go+w data.txt

Write protecting a file using chattr command

Let say you want to write protect the file called data.txt so that no other users can change it including root user, enter (you must login as the root user to use chattr command):
# chattr +i data.txt
To remove i attribute, enter:
# chattr -i data.txt

Share this tutorial on:

Your support makes a big difference:
I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft, takes a lot of my time and hard work to produce. If you use nixCraft, who likes it, helps me with donations:
Become a Supporter →    Make a contribution via Paypal/Bitcoin →   

Don't Miss Any Linux and Unix Tips

Get nixCraft in your inbox. It's free:



{ 4 comments… add one }
  • Esteban May 3, 2008, 12:13 pm

    incorrect syntax

    # chattar +i data.txt
    To remove i attribute, enter:

    this is the correct:

    # chattr +i data.txt
    To remove i attribute, enter:

  • nixCraft May 3, 2008, 12:19 pm

    The faq has been updated. Thanks for pointing out typo

  • luke June 26, 2014, 9:03 am

    you can still do operations like `mv` on the file depending on the directorys permissions in which the file resides. it would be important to consider this too.

  • vijay October 31, 2014, 10:17 am

    how to remove write protected file

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: , , , , , , , ,