背景

在尝试更新 Homebrew 时遇到以下错误:

1
2
3
brew update
fatal: could not read Username for 'https://github.com': terminal prompts disabled
Error: Fetching [redacted] failed!

问题排查

一开始以为是 Homebrew 本身的问题, 但运行 brew doctor 没有报异常和错误。 Homebrew 使用的是 git repo(从错误信息中可以看出),我想可能是 git repo 或 git 本身的问题。可以通过 cd $(brew --repo) 跳到 repo 文件夹。

经过调研, 发现问题的根本原因是 git 使用 https 进行身份验证,并且已经启用了 2FA。 可以通过强制 git 使用 SSH 协议来解决:

1
git config --global --add url."git@github.com:".insteadOf "https://github.com/"

完成上面的 git 设置后, 使用存放在 ~/.ssh 文件夹下的 keys 做身份认证, 关于如何配置 git 的 ssh_key,可以参考: Adding a new SSH key to your GitHub account

参考

  1. Fix git error: Could not read Username for github.com
  2. Git Error: Could could not read Username for Homebrew
  3. Adding a new SSH key to your GitHub account