macOS 包管理器 Homebrew 使用指南 🚀

Homebrew 是 macOS 上极为流行的包管理器,能够让你轻松安装和管理各种软件,让系统维护变得简单高效。🎉

一、Homebrew 的组成部分 🧩

Homebrew 主要由以下四个部分组成:

  1. brew:Homebrew 的核心命令行工具。
  2. homebrew-core:核心软件包仓库,包含常用的软件包公式。
  3. homebrew-bottles:预编译的二进制软件包,加快安装速度。⚡
  4. homebrew-cask:用于安装 macOS 图形界面的应用程序。🖥️

二、安装、更新和卸载 Homebrew 🔧

1. 安装 Homebrew 🛠️

步骤如下:

  1. 打开终端应用程序:你可以在“应用程序” > “实用工具”中找到,或者使用 Spotlight 搜索。🔍

  2. 运行以下命令安装 Homebrew:

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

    这个命令会自动下载并安装 Homebrew。📥

  3. 验证安装是否成功:

    brew doctor
    

    如果一切正常,会看到提示 Homebrew 安装成功的消息。✅

  4. 查看安装配置信息:

    brew --config
    

    这将显示 Homebrew 的版本、安装路径等详细信息。ℹ️

2. 使用 Homebrew 安装软件包 📦

安装成功后,你可以使用 Homebrew 安装各种软件。例如,安装 Git:

brew install git

Homebrew 会自动下载、编译并安装 Git,省时省力。⏱️

3. 更新 Homebrew 和软件包 🔄

更新 Homebrew:

brew update

这会更新 Homebrew 本身和软件包列表。📋

升级已安装的软件包:

brew upgrade

这将升级所有已安装的软件包到最新版本。若只想升级特定软件包:

brew upgrade [软件包名称]

更新通过 Homebrew Cask 安装的应用程序:

brew upgrade --cask

4. 卸载 Homebrew 和软件包 🗑️

卸载 Homebrew:

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

注意:卸载 Homebrew 会删除所有通过它安装的内容,请确保已经备份重要数据。⚠️

卸载单个软件包:

brew uninstall [软件包名称]

卸载通过 Homebrew Cask 安装的应用程序:

brew uninstall --cask [应用程序名称]

三、设置 Homebrew 的镜像源 🌐

如果下载速度较慢,可以更换为国内镜像源来加速。🚄

1. 查看当前镜像源 🔍

查看 brew.git 当前源:

cd "$(brew --repo)" && git remote -v

查看 homebrew-core.git 当前源:

cd "$(brew --repo homebrew/core)" && git remote -v

2. 更换为国内镜像源(以清华大学镜像为例) 🏫

更换 brew.git 镜像源:

cd "$(brew --repo)"
git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git

更换 homebrew-core.git 镜像源:

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

更新 Homebrew:

brew update

3. 更换 Homebrew Bottles 镜像源 🍾

对于 zsh 用户(macOS 10.15 及以上系统默认 shell):

echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.zshrc
source ~/.zshrc
brew update

对于 bash 用户:

echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.bash_profile
source ~/.bash_profile
brew update

四、常用的 Homebrew 命令 📝

1. 基础命令

  • 搜索软件包:

    brew search [关键词]
    
  • 列出已安装的软件包:

    brew list
    
  • 查看软件包信息:

    brew info [软件包名称]
    
  • 清理过期文件和缓存:

    brew cleanup
    
  • 显示 Homebrew 版本信息:

    brew --version
    
  • 获取帮助:

    brew help
    

2. 使用 brew services 管理后台服务 ⚙️

brew services 可以帮助你管理那些需要在后台运行的服务。

  • 启动服务并设置为开机自启:

    brew services start [服务名称]
    
  • 停止服务:

    brew services stop [服务名称]
    
  • 重启服务:

    brew services restart [服务名称]
    
  • 查看当前运行的服务:

    brew services list
    
  • 查看服务信息:

    brew services info [服务名称]