7.2 Shell 补全与命令缺失提示

原文链接: https://docs.brew.sh/Shell-Completion

原文链接: https://docs.brew.sh/Command-Not-Found

brew 的 shell 补全

Homebrew 为 Bash、fish 和 zsh 提供 brew 自身的补全定义,某些 formula 与外部命令还会为自己的命令提供补全。Homebrew 把补全文件存放在 HOMEBREW_PREFIX 下,系统 shell 默认不会自动搜索该目录,而安装器不会修改每种 shell 的启动配置(因为不同用户的启动文件和插件管理器差异很大)。

外部 Homebrew 命令提供的补全不会自动链接,启用方式:

1
brew completions link

Bash

把以下内容加入 ~/.bash_profile;当该文件不存在时加入 ~/.profile:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
if type brew &>/dev/null
then
  HOMEBREW_PREFIX="$(brew --prefix)"
  if [[ -r "${HOMEBREW_PREFIX}/etc/profile.d/bash_completion.sh" ]]
  then
    source "${HOMEBREW_PREFIX}/etc/profile.d/bash_completion.sh"
  else
    for COMPLETION in "${HOMEBREW_PREFIX}/etc/bash_completion.d/"*
    do
      [[ -r "${COMPLETION}" ]] && source "${COMPLETION}"
    done
  fi
fi

bash-completion formula 支持 macOS 自带的系统 Bash;使用 Homebrew 的 Bash 4 或更新版本时应安装 bash-completion@2。两个 formula 相互冲突,只能安装其中一个。上面的片段会加载已安装的那个版本,所以不要在 shell 配置的其他位置重复 source。

zsh

brew shellenv 会把 Homebrew 的 zsh 补全目录加入 FPATH。请确保 eval "$(brew shellenv)" 在 zsh 初始化补全之前执行,然后在 ~/.zshrc 中加入(若你的配置或框架没有调用 compinit):

1
2
autoload -Uz compinit
compinit

Oh My Zsh 加载时会自动调用 compinit,但请确认 brew shellenv 先被执行,Linux 上尤其重要。

如果 zsh 报告补全目录不安全,运行 compaudit 查看受影响的路径,只修复它列出的目录的属主与组/其他用户写权限。不要对整个 Homebrew 前缀递归改权限。

fish

Homebrew 的 fish formula 会自动发现 Homebrew 管理的补全。使用其他来源安装的 fish 时,在 ~/.config/fish/config.fish 中加入:

1
2
3
4
5
6
7
if test -d (brew --prefix)"/share/fish/completions"
    set -p fish_complete_path (brew --prefix)/share/fish/completions
end

if test -d (brew --prefix)"/share/fish/vendor_completions.d"
    set -p fish_complete_path (brew --prefix)/share/fish/vendor_completions.d
end

PowerShell

某些 formula 会在 Homebrew 的 PowerShell 补全目录中为自身命令安装补全;Homebrew 目前不提供 brew 自身的 PowerShell 补全定义。在 PowerShell profile(例如 ~/.config/powershell/Microsoft.PowerShell_profile.ps1)中加入:

1
2
3
4
5
if ((Get-Command brew -ErrorAction SilentlyContinue) -and (Test-Path ($completions = "$(brew --prefix)/share/pwsh/completions"))) {
  foreach ($f in Get-ChildItem -Path $completions -File) {
    . $f
  }
}

“命令找不到”时让 brew 给建议

在交互式 Bash、fish 或 zsh 中,Homebrew 可以查询 brew which-formula --explain,当某个缺失的可执行文件能由已知 formula 提供时,打印对应的安装命令。

先运行设置命令,它会输出适合当前 shell 的配置说明:

1
brew command-not-found-init

Bash/zsh 把输出的加载片段加入它提示的启动文件;fish 则加入 ~/.config/fish/config.fish。该加载器从当前 Homebrew 仓库加载,Homebrew 更新后会保持同步,因此不要把实现复制进配置。

配置后的效果类似:

1
2
3
$ example-command
The program 'example-command' is currently not installed. You can install it by typing:
  brew install example-formula

找不到匹配时,shell 仍会输出普通的 command-not-found 错误;该功能不会自动安装软件。