On Linux systems, set the immutable file attribute with chattr.
sudo chattr +i file
A file with the 'i' attribute cannot be modified: it cannot be deleted or renamed, no link can be created to this file, most of the file's metadata can not be modified, and the file can not be opened in write mode. Only the superuser or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.
lsattr to list a file's attributes.
lsattr -l myfile
The downside of doing this is that you won't be able to write to the file even as the superuser (root). You will need to remove the immutable attribute first:
sudo chattr -i file
On macOS, the chflags command is used to set and reset the immutable flag. To set:
chflags uchg file
and to unset, or clear:
chflags nouchg file
These operations may be performed by either the owner of a file or the superuser.
With macOS, using the
-Ol flags with
ls show the immutable flag as
uchg when set.