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.

Disclaimer:


The Sample Scripts provided below are adapted from third-party Open-Source sites.

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:

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:

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’.

Lock badge appears on app icon in Application tab

The app cannot be unlocked as Locked checkbox cannot be modified

Script to Unlock Files

To clear or remove this flag, run the command:

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.

Notes:

  • It is recommended to manually validate the script execution on a system before executing the action in bulk.
  • Hexnode will not be responsible for any damage/loss to the system on the behavior of the script.

  • Sample Script Repository