To write-protect a file on macOS (formerly OS X) from the command line, you can use the chflags
command with the uchg
flag.
Here’s an example command to write-protect a file named “example.txt” in the current directory:
sudo chflags uchg example.txt
The sudo
command is used to run the chflags
command with administrative privileges, which is required to change file flags. The uchg
flag sets the user immutable flag, which prevents any user (including the owner and administrator) from modifying or deleting the file.
If you want to remove the write protection, you can use the chflags
command again with the nouchg
flag:
sudo chflags nouchg example.txt
This will remove the user immutable flag and allow you to modify or delete the file again.