安装流程
1
下载 Git
2
安装配置
3
配置用户信息
4
GUI 客户端(可选)
Git 下载与安装
Git 官方
Windows 安装重要提示
推荐配置:安装过程中建议使用默认选项,以下配置需要注意:
- 默认编辑器:可选择 VS Code 或 Vim
- 分支命名:建议使用
main作为默认分支名 - PATH 配置:选择 "Git from command line and also from 3rd-party software"
- 行尾符:Windows 建议选择 "Checkout Windows-style, commit Unix-style line endings"
- 终端模拟器:选择 "Use MinTTY"
基础配置
用户信息配置
安装完成后,首先需要配置用户信息(全局配置):
1. 配置用户名
git config --global user.name "Your Name"
2. 配置邮箱
git config --global user.email "your.email@example.com"
3. 查看配置
# 查看所有配置
git config --list
# 查看用户信息
git config user.name
git config user.email
4. 常用全局配置
# 配置默认分支名
git config --global init.defaultBranch main
# 配置自动拉取合并
git config --global pull.rebase false
# 配置颜色显示
git config --global color.ui true
# 配置凭据助手(保存密码)
git config --global credential.helper store
Git GUI 客户端
建议:初学者可先用 GUI 熟悉操作,但建议尽快掌握命令行
GitHub Desktop
GitKraken
Sourcetree
TortoiseGit
常用 Git 命令
# 初始化仓库
git init
# 克隆远程仓库
git clone <repository-url>
# 查看状态
git status
# 添加文件到暂存区
git add <file>
git add . # 添加所有文件
# 提交更改
git commit -m "commit message"
# 查看提交历史
git log
git log --oneline # 简洁显示
# 创建新分支
git branch <branch-name>
# 切换分支
git checkout <branch-name>
# 创建并切换分支
git checkout -b <branch-name>
# 查看分支
git branch # 本地分支
git branch -a # 所有分支
# 合并分支
git merge <branch-name>
# 删除分支
git branch -d <branch-name>
# 推送分支到远程
git push origin <branch-name>
# 添加远程仓库
git remote add origin <repository-url>
# 查看远程仓库
git remote -v
# 拉取远程代码
git pull origin <branch-name>
# 推送代码
git push origin <branch-name>
# 首次推送并设置上游
git push -u origin <branch-name>
# 强制推送(慎用)
git push -f origin <branch-name>
# 撤销工作区修改
git checkout -- <file>
# 撤销暂存区文件
git reset HEAD <file>
# 修改最后一次提交
git commit --amend
# 回退到指定提交
git reset --hard <commit-id>
# 创建回退提交
git revert <commit-id>
常见问题与注意事项
# 1. 生成 SSH 密钥
ssh-keygen -t ed25519 -C "your.email@example.com"
# 2. 查看公钥内容
cat ~/.ssh/id_ed25519.pub
# Windows: type %USERPROFILE%\.ssh\id_ed25519.pub
# 3. 将公钥添加到 GitHub/Gitee 等平台
# 4. 测试连接
ssh -T git@github.com
ssh -T git@gitee.com
合并冲突时,Git 会在文件中标记冲突内容:
<<<<<<< HEAD
你的修改
=======
其他人的修改
>>>>>>> branch-name
解决步骤:
- 打开冲突文件,找到冲突标记
- 手动编辑,保留需要的内容
- 删除冲突标记(<<<<<<<、=======、>>>>>>>)
- 保存文件并重新提交
git add <file>
git commit -m "解决合并冲突"
.gitignore 文件用于指定哪些文件应该被 Git 忽略:
# 忽略所有 .log 文件
*.log
# 忽略 node_modules 目录
node_modules/
# 忽略 build 目录
build/
dist/
# 忽略环境变量配置文件
.env
.env.local
# 忽略 IDE 配置
.vscode/
.idea/
*.swp
*.swo
# 忽略系统文件
.DS_Store
Thumbs.db
# 忽略编译产物
*.class
*.pyc
__pycache__/
GitHub 官方 gitignore 模板
如果 Git 命令卡住或需要取消操作:
# 取消当前操作
Ctrl + C
# 退出 git log 等查看模式
q 键
# 退出 git commit 的编辑器模式
:wq # Vim 保存退出
:q! # Vim 不保存退出
# 取消合并
git merge --abort
# 取消 rebase
git rebase --abort