SIP preventing deletion of /opt/local Ran into the same problem tonight as this question from SO that wasn't fully answered.

I'm trying to uninstall an old installation of MacPorts, and run into SIP:

mybox:~ me$ sudo rm -rf /opt/local
rm: /opt/local/var/macports/home/Library/Preferences: Operation not permitted
rm: /opt/local/var/macports/home/Library: Operation not permitted
rm: /opt/local/var/macports/home: Operation not permitted
rm: /opt/local/var/macports: Directory not empty
rm: /opt/local/var: Directory not empty
rm: /opt/local: Directory not empty


According to the original question, the answer seems to involve SIP… but why has SIP decided to protect this (empty) directory?

EDIT: Here's the results of ls -a in the directory:

./ ../


And here's the results of ls -leOd /opt/local/var/macports/home/Library/Preferences:

drwxrwxrwx  2 root  wheel  - 64 Nov  8 19:45 /opt/local/var/macports/home/Library/Preferences/


.

EDIT 2018-11-12:

Here's the results of ls -laeO@ /opt/local/var/macports/home

drwxr-xr-x  3 root  wheel  - 96 Nov  8 19:42 ./
drwxr-xr-x@ 3 root  wheel  - 96 Nov  8 19:45 ../
    com.apple.FinderInfo    32 
drwxr-xr-x  3 root  wheel  - 96 Nov  8 19:42 Library/


EDIT 2018-11-13:

Here's the results of xattr -l /opt/local/var/macports

com.apple.FinderInfo:
00000000  00 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00  |........@.......|
00000010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  |................|
00000020
The directory is SIP-protected because it is the home directory for a macports user, presumably created as part of the MacPorts installation process. 

The best solution is to first remove that user account, following the instructions in this accepted answer to another AppleSE question. You may also wish to remove the corresponding macports group that also exists.

Specifically, the following commands will remove the user and group:

sudo /usr/bin/dscl . -delete "/Users/macports"
sudo /usr/bin/dscl . -delete "/Groups/macports"


The MacPorts website uninstall page mentions deleting the user and group but does not note that it is necessary due to SIP-protection to do this before deleting the folders. I think they also have an error in the syntax of their dscl command.

Once you have done that, you should be able to sudo rm -rf /opt/local successfully.

Significant credit for this answer is due to @GordonDavisson for providing 90% of the solution in comments, some months ago.