Mac – Can’t delete macports directory as root

macportsmojaveroot

I've enabled root user in my mac using the latest Mojave. I am trying to delete a folder with it but for some reason I get the error "Permission denied". I thought root could do anything on a unix system?

sh-3.2# whoami
root
sh-3.2# pwd
/opt/local/var/macports/home/Library
sh-3.2# ls -lhart
total 0
drwxr-xr-x  3 root  admin    96B Sep 24  2016 ..
drwxr-xr-x  3 root  admin    96B Sep 24  2016 .
drwxr-xr-x  2 root  admin    64B Oct 13 18:54 Preferences
sh-3.2# rm -rf Preferences/
rm: Preferences/: Operation not permitted
sh-3.2# whoami
root
sh-3.2#

Best Answer

Although System Integrity Protection will prohibit even the superuser from modifying system files, opt isn't included in that list. The issue is that all applications are fenced off from "important" bits of the filesystem by default and Terminal.app is no exception. In Mojave (OS X 10.14):

  • System Preferences
  • Security & Privacy
  • Privacy tab
  • Choose "Full Disk Access" from list on left
  • Click on "padlock" bottom-left and provide superuser password to elevate privileges and allow additions
  • Click on the "+" sign and navigate in file chooser to Terminal.app

Screenshots are available in http://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/.

You'll need to restart Terminal for the changes to take effect. The MacPorts uninstall command at https://guide.macports.org/chunked/installing.macports.uninstalling.html - at the time of writing, this:

sudo rm -rf \
        /opt/local \
        /Applications/DarwinPorts \
        /Applications/MacPorts \
        /Library/LaunchDaemons/org.macports.* \
        /Library/Receipts/DarwinPorts*.pkg \
        /Library/Receipts/MacPorts*.pkg \
        /Library/StartupItems/DarwinPortsStartup \
        /Library/Tcl/darwinports1.0 \
        /Library/Tcl/macports1.0 \
        ~/.macports

...should now work.

As a side-note, current versions of iTerm request this permission when first installed and run, so if you have iTerm kicking around and don't want to restart Terminal, add it to the "Full Disk Access" list (if it isn't added already) and run the command there.