Homebrew 安装与国内镜像配置

一、全新安装 Homebrew(中科大镜像加速)

  1. 安装前准备
# 确保 /opt/homebrew 目录存在且归属当前用户(M芯片专用路径)
sudo mkdir -p /opt/homebrew  # 需临时sudo创建目录
sudo chown -R $(whoami) /opt/homebrew  # 立即将所有权归还用户
  1. 使用国内镜像脚本安装(解决官方脚本下载慢)
# 使用中科大镜像的安装脚本(自动配置仓库地址)
/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
​​选项说明​​:
    输入 `1` 选择 `​​中科大源`​​。
    按提示完成安装,脚本会自动处理镜像配置。

二、手动配置镜像(适用于已安装 Homebrew 的情况)

  1. 替换核心仓库地址
# 主仓库 (brew.git)
git -C "$(brew --repo)" remote set-url origin https://mirrors.ustc.edu.cn/brew.git

# 核心软件包仓库 (homebrew-core)
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-core.git

# Cask 软件仓库 (可选,如需安装 GUI 软件,如 VSCode、Chrome)
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-cask.git
  1. 配置二进制预编译包镜像
# 写入环境变量(永久生效)
echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles/bottles' >> ~/.zshrc
source ~/.zshrc

三、验证配置

# 检查远程仓库地址
git -C "$(brew --repo)" remote -v  # 应显示中科大地址
git -C "$(brew --repo homebrew/core)" remote -v
git -C "$(brew --repo homebrew/cask)" remote -v  # 可选 

# 更新 Homebrew
brew update  # 应无权限报错

# 测试安装
brew install wget  # 观察下载是否走中科大镜像

四、常见问题修复

  1. 目录权限被篡改(如之前误用 sudo)
# 强制修复整个 Homebrew 目录权限
sudo chown -R $(whoami) /opt/homebrew
  1. Git 安全警告(可疑仓库所有权)
# 添加安全目录例外(仅临时方案,优先用 chown 修复)
git config --global --add safe.directory /opt/homebrew/Library/Taps/homebrew/homebrew-core

五、恢复官方源(备用)

# 重置仓库地址
git -C "$(brew --repo)" remote set-url origin https://github.com/Homebrew/brew.git
git -C "$(brew --repo homebrew/core)" remote set-url origin https://github.com/Homebrew/homebrew-core.git
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://github.com/Homebrew/homebrew-cask.git

# 删除镜像环境变量
sed -i '' '/HOMEBREW_BOTTLE_DOMAIN/d' ~/.zshrc
source ~/.zshrc
posted @ 2025-05-03 13:13  Ritchie^._.^  阅读(1389)  评论(0)    收藏  举报