macOS 下/usr/local/目录下Operation not permitted的问题

问题

这个状况在尤为是在brew的使用过程当中会出现,具体表现为:shell

Error: /usr/local is not writable. You should change the ownership
and permissions of /usr/local back to your user account:
  sudo chown -R $(whoami) /usr/local

若是你按照他的要求执行chown -R,很大几率下你会遇到下列错误less

chown: /usr/local: Operation not permitted
chown: /usr/local/Cellar: Operation not permitted
......

缘由和解决方法

形成这个问题的实际缘由是Apple的 Rootless(System Integrity Protection) 策略。rest

"Operation not permitted"并非由于权限问题(权限问题能够用chown或者chmod来解决),而是触发了macOS的SIP保护。code

SIP标识符:restricted

遇到这个问题时,若是你使用ls -lO 查看/usr/local,你会发现下面的大部分文件都被打上了restricted标志。ip

total 0
drwxrwxrwx    2 root  wheel  restricted   64 10  9 18:07 Caskroom
drwxrwxrwx   53 root  wheel  restricted   1696 10 10 17:13 Cellar
drwxrwxrwx    4 root  wheel  restricted   128 11 19  2019 Frameworks
drwxrwxrwx   20 root  wheel  -            640 10 10 17:12 Homebrew
drwxrwxrwx  243 root  wheel  restricted   7776 10 10 17:13 bin
drwxrwxrwx   26 root  wheel  -            832 10  9 18:20 etc
drwxrwxrwx   67 root  wheel  restricted   2144 10 10 17:13 include
drwxrwxrwx  196 root  wheel  restricted   6272 10 10 17:13 lib
drwxrwxrwx    4 root  wheel  -            128 10 10 16:24 libexec
drwxrwxrwx   75 root  wheel  -            2400 10 10 17:13 opt
drwxrwxrwx    9 root  wheel  restricted   288 10  9 18:16 sbin
drwxrwxrwx   29 root  wheel  restricted   928 10 10 17:13 share
drwxrwxrwx    3 mzy   wheel  -            96  4 16  2018 texlive
drwxrwxrwx    8 root  wheel  -            256 10  9 18:23 var

这个标志的用途就是告诉macOS的SIP,这个文件受到系统保护,不能更改。terminal

解除保护的命令就一句话
chflags -R norestricted .
即可以把当前目录以及他们子目录下的全部文件解除保护(连接除外,需手动处理)
可是若是你的macOS正处于SIP保护下,你是无权执行该命令的。
查看SIP保护状态,只须要在terminal里输入
csrutil status
若是显示System Integrity Protection status: enabled. 则意味着SIP做动中。it

取消SIP保护

重启电脑,按Command+R进入恢复模式,打开恢复模式下的终端。
在这里cd /Volumes/你的硬盘名/usr
再执行chflags就能够解除这些文件夹的SIP保护了。
我并不建议你使用csrutil disable来关闭SIP保护,由于这可能使系统陷入风险。io

相关文章
相关标签/搜索