# 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](https://www.hexnode.com/mobile-device-management/help/how-to-run-scripts-on-mac-using-hexnode-mdm/) 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:

Script to lock files on Mac

chflags schg <path> 

   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:

Sample script

Shell

chflags schg /Applications/WhatsApp.app 

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

![Lock badge appears on app icon in Application tab ](https://cdn.hexnode.com/mobile-device-management/help/wp-content/uploads/2022/03/Lock-badge-on-app-icon-1024x509.png)![The app cannot be unlocked as Locked checkbox cannot be modified ](https://cdn.hexnode.com/mobile-device-management/help/wp-content/uploads/2022/08/Locked-checkbox-greyed-out.png)Script to Unlock Files
----------------------

To clear or remove this flag, run the command:

Sample script

Shell

chflags noschg <path> 

   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.

 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.