79758041

Date: 2025-09-07 09:37:32
Score: 0.5
Natty:
Report link

Answer

Homebrew casks use sudo -u root -E to preserve environment variables when managing LaunchDaemon plist files during upgrades. The error occurs because:

  1. Default macOS security: sudoers has env_reset which clears environment variables.
  2. Missing permission: Users lack SETENV capability needed for sudo -E.
  3. Command conflict: The -E flag conflicts with the env_reset policy.

The Fix

Method 1: Dual sudoers approach (Recommended)

# Get your username
USER=$(whoami)

# Add to sudoers.d (modular approach)
echo "$USER ALL=(ALL) SETENV: ALL" | sudo tee /etc/sudoers.d/homebrew

# Add to main sudoers (ensures compatibility)
echo -e "\n# Homebrew sudo -E fix\n$USER ALL=(ALL) SETENV: ALL" | sudo tee -a /etc/sudoers

Method 2: One-liner version

USER=$(whoami) && \
echo "$USER ALL=(ALL) SETENV: ALL" | sudo tee /etc/sudoers.d/homebrew && \
echo -e "\n# Homebrew sudo -E fix\n$USER ALL=(ALL) SETENV: ALL" | sudo tee -a /etc/sudoers

Verification Steps

  1. Check sudo permissions:

    sudo -l
    

    Look for: (ALL) SETENV: ALL in the output.

  2. Test environment preservation:

    sudo -E echo "Environment test successful"
    

    Should work without errors.

  3. Test Homebrew upgrade:

    brew upgrade --greedy
    

    The environment preservation errors should be gone.


What This Does


Expected Results

Before fix:

sudo: sorry, you are not allowed to preserve the environment
Error: Failure while executing; /usr/bin/sudo -u root -E -- /bin/rm -f -- /Library/LaunchDaemons/...

After fix:

==> Removing launchctl service com.adobe.ARMDC.Communicator
==> Upgrading adobe-acrobat-reader
# Upgrade proceeds normally

Why Both sudoers Locations?

Some systems require the permission in the main sudoers file rather than sudoers.d. The dual approach ensures maximum compatibility across different macOS configurations and security policies.


Rollback

To remove the fix:

sudo rm /etc/sudoers.d/homebrew

Then manually edit /etc/sudoers with visudo to remove the added lines.


Security Notes


Affected Applications

This fix resolves issues with casks that install LaunchDaemons:


Tested on: macOS Sequoia 15.2, Homebrew 4.4.11

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Bram Alkema