Category filter
Script to Prevent File Modification on Mac
Macs allow files to be locked to prevent them from being modified or deleted accidentally by a user. Using chflags utility, protect important files from modification such that users of any privilege are locked out. With Hexnode, use custom scripts to lock and unlock files on your macOS devices.
Script to Lock Files
To set up a write protection, you need to assign an immutable flag to the file. Once this is set up, no one can delete or modify the file, including root admin. Only the root admin can clear the immutable bit.
Use the command:
1 |
chflags schg <path> |
chflag
– Modifies the file flags of listed files.
schg
– Set the system immutable flag, which locks out all modifications from users with any privileged level.
path
– The location of the app or the file that should be protected.
For example:
1 |
chflags schg /Applications/WhatsApp.app |
On running this command, a lock badge appears on the app icon. On taking a closer look using the Get Info shortcut, the checkbox next to “Locked” is checked and greyed out. If you try to delete or modify the app you will receive a window that says ‘The operation can’t be completed because the item is locked’.
Script to Unlock Files
To clear or remove this flag, run the command:
1 |
chflags noschg <path> |
This command removes the flag and removes the lock badge on the app icon. The app or file can now be modified or deleted by the user.