In macOS, checking the \”Locked\” box in the graphical Get Info window is usually enough to prevent accidental deletion of a file. However, for system administrators, advanced users, or scripts requiring unbreakable protection against deletion, modification, or even viewing, the standard graphical tools are insufficient. To enforce strict file immutability at the lowest levels of the Apple File System (APFS), you must use the macOS chflags command in the terminal.
Why Use the chflags Command?
The chflags command (change flags) operates at a deeper level than standard UNIX file permissions (read, write, execute). It modifies the fundamental system flags associated with a file’s inode. If a file has the \”immutable\” flag set, no one—not even the root user or a sudo command—can delete, rename, or alter the file until the flag is explicitly removed. This is critical for protecting server configuration files, vital bash scripts, or sensitive financial data from both accidental user error and malicious software tampering.
Step 1: Lock a File Against Deletion (User Immutable)
The most common use case is applying the User Immutable flag (uchg). This prevents the file from being changed or deleted, but the owner of the file can unlock it.
- Open the macOS Terminal.
- Type the following command, but do not press enter yet:
chflags uchg
- Drag and drop the file you want to protect into the terminal window to auto-fill its path. The final command will look like
chflags uchg /Users/Name/Desktop/budget.xlsx. - Press Enter. The file is now locked. You cannot delete it, move it to the trash, or edit its contents.
Step 2: Apply the System Immutable Flag
For extreme security, you can apply the System Immutable flag (schg). Once applied, not even the root user can remove this lock while the Mac is running normally (it must be removed in Single User Mode or Recovery Mode).
- Run the command using sudo:
sudo chflags schg /path/to/critical_system_file.conf
Step 3: Hide a File from the Graphical Finder
The chflags command can also manipulate visibility flags. If you want to hide a sensitive folder so it does not appear on your desktop or in the Finder, use the hidden flag.
- Run the following command:
chflags hidden /Users/Name/Desktop/SecretFolder
The folder will instantly vanish from the graphical interface, but it still exists and can be accessed via the terminal.
Step 4: Remove Flags to Unlock Files
To reverse any flag, simply prepend the flag name with the word no.
- To unlock a user-immutable file so you can delete it:
chflags nouchg /path/to/file
- To unhide a folder so it appears in the Finder again:
chflags nohidden /path/to/SecretFolder
By mastering the chflags command, macOS administrators can enforce strict, unbreakable security policies on sensitive data, ensuring files cannot be tampered with or deleted by unauthorized processes.