Homebrew 安装以及配置国内镜像

上班之后公司给配了 macOS 系统的电脑,目前的配置是 20 年的顶配(虽然更希望能拿到 M 芯片的机器,但还是挺好用),到手之后有些不适应,同事推荐我一定要安装 homebrew,于是我就开始了 Homebrew 的安装和配置。

1. 安装 Homebrew

在终端中执行以下命令安装 Homebrew:

1
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

安装完成后,按照终端提示将 Homebrew 的路径加入到 ~/.zprofile~/.zshrc 中。

2. 配置国内镜像源

为加速 Homebrew 的软件包下载,可以将默认源替换为国内镜像。以清华大学镜像为例:

1
2
3
4
5
6
7
8
# 替换 Homebrew 主仓库
cd "$(brew --repo)" && git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git

# 替换 Homebrew Core
cd "$(brew --repo homebrew/core)" && git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git

# 替换 Homebrew Bottles
export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles

可以将 HOMEBREW_BOTTLE_DOMAIN 这一行添加到 ~/.zshrc~/.bash_profile 以便每次终端启动时自动生效。

3. 恢复官方源(可选)

如果需要恢复为官方源,可以执行:

1
2
3
cd "$(brew --repo)" && git remote set-url origin https://github.com/Homebrew/brew.git
cd "$(brew --repo homebrew/core)" && git remote set-url origin https://github.com/Homebrew/homebrew-core.git
unset HOMEBREW_BOTTLE_DOMAIN

4. 遇到的问题

  • 安装完之后执行 brew --version 出现 zsh: command not found: brew 错误,是因为 Homebrew 的路径没有添加到环境变量中。可以通过以下命令手动添加:
1
2
echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zprofile
source ~/.zprofile

5. 总结

homebrew 在 MacOS 上确实好用,安装 git、node、python 等常用工具非常方便,对开发者简直太友好,且有国内镜像源可以加速下载,perfect!