MacOS编辑launchd.conf时遇权限拒绝错误求助
First off, the "Permission denied" error pops up because /etc is a system-protected directory—regular user accounts don’t have write access to it. Let’s fix that, plus cover a critical note for modern macOS versions since launchd.conf isn’t the most reliable approach anymore.
Step 1: Edit the file with admin privileges
Instead of running just nano /etc/launchd.conf, use sudo to gain root-level access:
sudo nano /etc/launchd.conf
When prompted, enter your user account password (you won’t see characters as you type—this is normal for sudo prompts).
Step 2: Add your environment variables
Paste these two lines into the file:
setenv OPENCV_ANDROID_SDK /Users/kang/Desktop/OpenCV-android-sdk/OpenCV-android-sdk setenv EIGEN3_DIR /Users/kang/Desktop/OpenCV-android-sdk/eigen3
Save the file by pressing Ctrl+O, hit Enter to confirm the filename, then exit with Ctrl+X.
Step 3: Make variables take effect (and a key warning)
If you run echo $OPENCV_ANDROID_SDK $EIGEN3_DIR right away, you won’t see the values—launchd.conf is only read when launchd starts up (on system boot or user login). To apply them immediately without restarting, run these commands:
launchctl setenv OPENCV_ANDROID_SDK /Users/kang/Desktop/OpenCV-android-sdk/OpenCV-android-sdk launchctl setenv EIGEN3_DIR /Users/kang/Desktop/OpenCV-android-sdk/eigen3
Now echo should display your paths correctly.
Important: Modern macOS (Catalina 10.15+) ignores /etc/launchd.conf
System Integrity Protection (SIP) blocks launchd from reading the global /etc/launchd.conf file. Even if you edit it with sudo, your variables won’t persist after a reboot. A better, supported alternative is to create a user-specific launch agent:
- Create a plist file in your user’s LaunchAgents directory:
nano ~/Library/LaunchAgents/com.user.environment.plist
- Paste this content (double-check the paths match your setup):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.user.environment</string> <key>ProgramArguments</key> <array> <string>sh</string> <string>-c</string> <string> launchctl setenv OPENCV_ANDROID_SDK /Users/kang/Desktop/OpenCV-android-sdk/OpenCV-android-sdk; launchctl setenv EIGEN3_DIR /Users/kang/Desktop/OpenCV-android-sdk/eigen3 </string> </array> <key>RunAtLoad</key> <true/> </dict> </plist>
- Save and exit the file (
Ctrl+O, Enter,Ctrl+X). - Load the agent to apply changes immediately:
launchctl load ~/Library/LaunchAgents/com.user.environment.plist
This agent will run every time you log in, so your environment variables will stay active across reboots.
内容的提问来源于stack exchange,提问作者kangdawei

