Apple OS X: Write Protect File From Command Line

How do I make a File “unalterable” (write protect) such as it cannot be changed or deleted even by root or superuser under Apple OS X UNIX operating systems?

You can make a file unalterable i.e write protect it but root / superuser can always make changes using the same method. In other words, you can not write protect your stuff from root. Linux use can use the chattr command for write protecting the files.

Change File Flags With the chflags Command

The chflags command modifies the file flags. First, open the terminal and to set system immutable flag type the following command:

sudo chflags schg fileName

The owner can set the user immutable flag as follows (no need to use sudo or superuser password):

chflags uchg fileName

In this, example set user immutable flag on resume.txt file, enter:

chflags uchg resume.txt

To list flags, enter:

ls -lO resume.txt

Sample outputs:

-rw-r--r--  1 vivek  wheel  uchg 18424 Jun  2 18:48 resume.txt

Now, try deleting or writing to the same file, enter:
rm resume.txt
Sample outputs:

override rw-r--r--  vivek/wheel uchg for resume.txt? y
rm: resume.txt: Operation not permitted

How Do I Remove User Immutable Flag?

Use the command as follows:

chflags nouchg resume.txt
ls -lO resume.txt

Sample outputs:

-rw-r--r--  1 vivek  wheel  - 18424 Jun  2 18:48 resume.txt

Putting the letters no before causes the flag to be cleared.

How Do I Remove System Immutable Flag?

Use the command as follows:

sudo chflags noschg resume.txt
ls -lO resume.txt<

Please note that above commands works on both the file and folder (remember, under UNIX everything is file).

Finder GUI Tool Method

Right click or control+click (command + I does the same thing) the file or folder you want to write protect and select Get Info. You will get info window as follows:

Fig.01: Apple OS X UNIX – Protecting files and folders

Click a small lock icon (located at bottom right) and provide your admin password. Once authenticated click on “Locked” check box to lock the file (this is same as running the above chflags command). Additionally, you can add or remove user write permission too.

Recommend Readings:

For more information on use of the chflags utility and additional options, please refer to the chflags man page, viewable by typing man chflags from the command line:
man chflags

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.