How do I run Homebrew as root?

Solution 1:

After making your change to the script, try setting the immutable flag on brew.sh.

chflags uchg /usr/local/Homebrew/Library/Homebrew/brew.sh

I have not tested. As a general rule, I do not give root to applications whose developers are begging me not to.

Solution 2:

Typical users shouldn't do this, but you're not typical are you?

Two issues:

  1. You can't stop root. If you insist on using root, then root can overwrite brew.sh no matter what.

  2. You can't stop brew, after all, you're talking about running brew.

So we'll work with that. Let's setup an alias to copy over brew.sh then run brew.

alias brew='cp /<modified>/brew.sh /<actuall>/brew.sh; /usr/local/bin/brew'

(Fix the paths to match your system).

Now all you need to do is:

sudo brew <arguments>

(It'll become root, copy over brew.sh, then run brew as root with arguments, afterwards brew will overwrite brew.sh and you'll be ready to do it all over again)

Note: You could put sudo into the alias too, but this way feels better because you'll be prompted for a password every time.

Typically you can't use setuid (chmod u+s) to root on shell scripts, for security. Perl has a separate program suidperl that could be installed and could escalate user privilege, but such solutions are a bit deep for a quick answer.