一、安装 git
方法 1:通过 homebrew 安装(推荐)
安装 homebrew(若未安装):
/bin/bash -c "$(curl -fssl https://raw.githubusercontent.com/homebrew/install/head/install.sh)"
• 安装完成后,重启终端。
通过 homebrew 安装 git:
brew install git
验证安装:
git --version
• 输出类似 git version 2.39.0 表示成功。
方法 2:通过 xcode command line tools 安装
安装 xcode command line tools:
xcode-select --install
系统会弹出图形化安装界面,按提示完成安装。
验证 git 是否自带安装:
git --version
macos 默认会安装 git,但版本可能较旧(如 2.37.0)。
方法 3:手动下载安装包
- 访问 git 官网下载页面:
https://git-scm.com/download/mac - 下载
.dmg文件(如git-2.39.0-intel-universal-mavericks.dmg)。 - 挂载并安装:
• 双击下载的.dmg文件,将 git.app 拖入 applications 文件夹。 - 配置环境变量:
# 将 git 添加到 path(若手动安装未自动配置) echo 'export path="/applications/git.app/contents/resources/bin:$path"' >> ~/.zshrc source ~/.zshrc
二、基础配置
1. 设置全局用户名和邮箱
git config --global user.name "your name" git config --global user.email "your.email@example.com"
• 验证配置:
git config --global --list
2. 配置 ssh 密钥(用于 github/gitlab 等)
生成 ssh 密钥:
ssh-keygen -t ed25519 -c "your.email@example.com"
• 按提示保存密钥到默认路径(~/.ssh/id_ed25519)。
• 设置密钥密码(可选)。
将公钥添加到 github/gitlab:
• 复制公钥内容:
cat ~/.ssh/id_ed25519.pub
• 登录 github → settings → ssh and gpg keys → 添加新 ssh key。
测试 ssh 连接:
ssh -t git@github.com
• 成功提示:hi username! you've successfully authenticated.
3. 配置 git 别名(简化命令)
git config --global alias.co checkout git config --global alias.br branch git config --global alias.st status git config --global alias.lg "log --oneline --graph --all"
• 示例:git st 等同于 git status。
4. 启用 git 自动换行符转换
git config --global core.autocrlf input # macos/linux git config --global core.safecrlf warn # 检测混合换行符
三、高级设置
1. 配置差异工具(如 beyond compare)
- 安装 beyond compare(需购买或下载试用版)。
- 配置 git 调用 beyond compare:
git config --global merge.tool bc3 git config --global mergetool.bc3.path "/applications/beyond compare.app/contents/macos/bcomp"
2. 配置 git 代理(解决网络问题)
# http/https 代理 git config --global http.proxy http://127.0.0.1:7890 git config --global https.proxy https://127.0.0.1:7890 # socks5 代理(如 clash) git config --global http.proxy socks5://127.0.0.1:7890 git config --global https.proxy socks5://127.0.0.1:7890 # 取消代理 git config --global --unset http.proxy git config --global --unset https.proxy
四、常见问题与解决方法
1. 安装失败:error: the following directories are not writable by your user
• 解决:使用 sudo 或修复目录权限:
sudo chown -r $(whoami) /usr/local/*
2. 权限错误:permission denied (publickey)
• 解决:
确认 ssh 密钥已添加到 ssh-agent:
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519
检查公钥是否正确添加到 github/gitlab。
3. git 版本过旧
• 升级 git:
brew update && brew upgrade git
4. 终端提示git: command not found
• 解决:
• 检查是否已安装 git:which git。
• 若未安装,通过上述方法重新安装。
• 确保 git 路径在环境变量中(echo $path)。
五、卸载 git
# 通过 homebrew 卸载 brew uninstall git # 手动删除(若通过 dmg 安装) sudo rm -rf /applications/git.app sudo rm -rf /usr/local/git
到此这篇关于macos系统下git的详细安装步骤与基础设置指南的文章就介绍到这了,更多相关macos git安装与配置内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论