For years, the Macintosh operating system has allowed you to lock a file or folder to protect against accidental deletion or modification. In OS X, you have that same ability, either through the Finder or the shell.
If there's one thing that friends and family know, it's how to find that one file you've been spending an inordinate amount of time on and then delete it in a fit of gleeful innocence. For many years in Mac OS 9 and earlier, the first line of defense for this behavior has been locking a file, making sure that it can't be changed or deleted unless it is specifically unlocked.
This ability remains in Mac OS X and applies even to the root user (locked files can't be deleted without being unlocked first, period). Longtime Mac users are familiar with the following process for locking a file or directory in the Finder:
Select the file or directory you want to lock.
Choose Get Info from the File menu or press -I.
Place a check in the Locked checkbox.
Either of the following two shell commands do the same thing under OS X:
% chflags uchg filename.txt % /Developer/Tools/SetFile -a L filename.txt
The chflags utility is part of a default OS X install and changes the uchg flag of a file, representing the immutable bit (literally, "this file is not subject to change"). chflags can be performed only by a superuser or the file's owner. SetFile is a utility that comes with the Developer Tools and operates on a file's attributes (attributes and flags can be considered equivalent). In this case, you're saying the locked attribute (-a L) of the file should be set.
Via the Finder, you can tell when a file is locked because it'll have a padlock icon superimposed over the lower left of its normal icon, as shown in Figure 1-16.
In the Terminal [Hack #48], you can type ls -ol (o to show the file flags, and l for long listing). Any file with the uchg flag is locked:
% ls -ol filename.txt -rw-r--r-- 1 morbus staff uchg 0 Dec 4 01:07 filename.txt
Unlocking is a simple matter of reversal. Either uncheck the locked checkbox in the file's Get Info inspector or enter one of the following shell commands:
% chflags nouchg filename.txt % /Developer/Tools/SetFile -a L filename.txt
Nothing really surprising there. To unset a uchg or any other file flag using the chflags utility, simply prefix the flag name with no. When using SetFile, simply reverse the case of the attribute letters; uppercase letters always add the flag to the file, and lowercase letters remove the flag.
For details on chflags and SetFile, at the Terminal [Hack #48], type man chflags and man SetFile, respectively.