目录
-
前置条件
-
安装 Git
-
配置 Git
-
生成 SSH Key(推荐方式)
-
将 SSH Key 添加到 GitHub/GitLab
-
克隆(拉取)项目
-
常见问题排查
1. 前置条件
-
一台运行 macOS 的电脑
-
已安装 Xcode Command Line Tools(Git 和编译工具依赖)
-
GitHub、GitLab 或其他 Git 平台账号
-
项目仓库地址(可为 SSH 或 HTTPS 格式)
2. 安装 Git
方法一:通过 Homebrew 安装(推荐)
brew install git
安装完成后,输入以下命令检查是否安装成功:
git --version
输出示例:
git version 2.42.0
方法二:通过 Xcode 命令行工具安装
xcode-select --install
安装完成后即可使用 Git。
3. 配置 Git
首次使用 Git,需配置用户名和邮箱:
git config --global user.name "你的用户名"
git config --global user.email "你的邮箱@example.com"
查看当前的 Git 配置信息:
git config --global --list
4. 生成 SSH Key(推荐方式)
为了避免频繁输入用户名和密码,建议使用 SSH 方式连接仓库。
生成 SSH 密钥
ssh-keygen -t ed25519 -C "你的邮箱@example.com"
按提示一路回车,默认会生成以下两个文件:
-
私钥:
~/.ssh/id_ed25519
-
公钥:
~/.ssh/id_ed25519.pub
启动 SSH agent 并添加私钥
eval "$(ssh-agent -s)"
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
5. 将 SSH Key 添加到 GitHub/GitLab
复制公钥内容到剪贴板
pbcopy < ~/.ssh/id_ed25519.pub
添加到 Git 平台
-
GitHub: 登录后进入 https://github.com/settings/keys
-
GitLab: 登录后进入 https://gitlab.com/-/profile/keys
点击 "New SSH Key",粘贴内容,填写标题,保存即可。
6. 克隆(拉取)项目
使用 SSH 地址克隆项目(推荐)
git clone git@github.com:用户名/仓库名.git
示例:
git clone git@github.com:octocat/Hello-World.git
使用 HTTPS 地址克隆项目(不推荐)
git clone https://github.com/用户名/仓库名.git
这种方式在每次推送或拉取时通常会要求输入用户名和密码(或者令牌),不够方便。
7. 常见问题排查
问题 1:找不到 git 命令
错误提示:
zsh: command not found: git
解决方法:确认是否已正确安装 Git,可以使用 brew install git
重新安装。
问题 2:SSH 报错:Permission denied (publickey)
可能原因及解决方案:
-
公钥未添加到 Git 平台账号中
-
Git URL 使用错误,应使用 SSH 格式:
git@github.com:xxx/xxx.git
-
未启动 SSH agent,或未添加 SSH key:重新运行以下命令:
eval "$(ssh-agent -s)"
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
参考资料
-
Git 官方网站:Git
-
GitHub SSH 配置指南:Connecting to GitHub with SSH - GitHub Docs
-
Homebrew 官网:Homebrew --- The Missing Package Manager for macOS (or Linux)