Skip to content

在中国大陆使用 Homebrew,由于网络原因,直接从官方源(GitHub)下载速度很慢,甚至会失败。因此,切换到国内镜像是非常有必要的。以下是几个最常用、最稳定的镜像源:

  1. 清华大学 TUNA 镜像源

  2. 中国科学技术大学 (USTC) 镜像源

    • 特点:同样非常稳定和快速,和清华源一样,是学术界和开发者社区的流行选择。
    • 官网https://mirrors.ustc.edu.cn/
    • 镜像地址mirrors.ustc.edu.cn
  3. 阿里云 (Aliyun) 镜像源

    • 特点:由商业公司维护,CDN 加速,速度非常快,尤其适合在阿里云服务器上使用,个人用户使用体验也极佳。
    • 官网https://developer.aliyun.com/mirror/
    • 镜像地址mirrors.aliyun.com
  4. 腾讯云 (Tencent Cloud) 镜像源

选择建议

  • 首选:清华大学 TUNA 源或中科大 USTC 源,它们是社区公认的稳定可靠的选择。
  • 速度优先:可以尝试阿里云或腾讯云,它们的 CDN 网络可能在某些地区提供更快的下载速度。

如何切换 Homebrew 镜像源

切换 Homebrew 源主要涉及三个部分:

  1. Homebrew 核心仓库 (brew.git)brew 命令本身。
  2. 主要的软件仓库 (homebrew-core.githomebrew-cask.git):包含所有软件包的定义。
  3. 预编译二进制包 (bottles)brew install 时下载的预编译文件,这是提升速度的关键。

很多镜像源官方都提供了自动配置脚本,可以一键完成所有配置,非常方便。

例如使用清华大学 TUNA 镜像源脚本:

执行以下命令即可自动完成 Homebrew 以及核心软件仓库的镜像替换:

bash
# 替换 brew.git、homebrew-core.git 和 homebrew-cask.git 等
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git
# 注:自 brew 4.0.0 (2023 年 2 月 16 日) 起,HOMEBREW_INSTALL_FROM_API 会成为默认行为,无需设置。大部分用户无需再克隆 homebrew-core 仓库,故无需设置 HOMEBREW_CORE_GIT_REMOTE 环境变量;但若需要运行 brew 的开发命令或者 brew 安装在非官方支持的默认 prefix 位置,则仍需设置 HOMEBREW_CORE_GIT_REMOTE 环境变量。如果不想通过 API 安装,可以设置 HOMEBREW_NO_INSTALL_FROM_API=1。
# git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git
# 注:目前,homebrew-cask-{drivers,versions,fonts} 已被弃用,所有 cask 合并至 homebrew-cask 仓库。
# git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git

# 替换 bottles 源
# 注意:根据你的 shell 修改配置文件名,zsh 用 .zshrc, bash 用 .bash_profile
# 对于 Zsh 用户
echo 'export HOMEBREW_API_DOMAIN="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/api"' >> ~/.zshrc
echo 'export HOMEBREW_BOTTLE_DOMAIN="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles"' >> ~/.zshrc
source ~/.zshrc

# 对于 Bash 用户
echo 'export HOMEBREW_API_DOMAIN="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/api"' >> ~/.bash_profile
echo 'export HOMEBREW_BOTTLE_DOMAIN="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles"' >> ~/.bash_profile
source ~/.bash_profile

# 最后刷新
brew update