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

相關文章
相關標籤/搜索