基本 Git 命令参考
Git 是使用最广泛的分布式版本控制系统。本参考涵盖最重要的命令,并提供日常开发工作流程中的实用示例。

配置
# 设置用户身份(首次提交前必需)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
# 设置默认编辑器
git config --global core.editor "code --wait"
# 设置默认分支名称
git config --global init.defaultBranch main
# 查看所有配置
git config --list
# 查看特定设置
git config user.email
仓库设置
# 初始化新仓库
git init
git init my-project
# 克隆远程仓库
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git custom-folder
# 仅克隆特定分支
git clone -b develop https://github.com/user/repo.git

日常工作流程命令
# 检查工作目录状态
git status
git status -s # 简短格式
# 暂存更改
git add file.txt # 暂存特定文件
git add . # 暂存所有更改
git add -p # 交互式暂存(补丁模式)
git add src/ # 暂存整个目录
# 提交
git commit -m "feat: add user authentication"
git commit -am "fix: correct typo" # 暂存已跟踪文件并提交
git commit --amend # 修改上次提交信息或添加暂存的更改
# 查看历史
git log
git log --oneline # 每行一个提交
git log --oneline --graph # 分支的 ASCII 图
git log -n 10 # 最近 10 次提交
git log --since="2 weeks ago"
git log --author="Alice"
git log --grep="login" # 搜索提交信息
分支操作
# 创建并切换到新分支
git checkout -b feature/login # 传统方式
git switch -c feature/login # 现代方式(Git 2.23+)
# 切换分支
git checkout main
git switch main
# 列出分支
git branch # 本地分支
git branch -a # 所有分支(本地 + 远程)
git branch -v # 显示每个分支的最后一次提交
# 删除分支
git branch -d feature/done # 安全删除(仅已合并)
git branch -D feature/old # 强制删除
# 重命名当前分支
git branch -m new-name

远程操作
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 查看远程仓库
git remote -v
# 获取(下载更改,不合并)
git fetch origin
git fetch --all
# 拉取(获取 + 合并)
git pull origin main
git pull --rebase origin main # 使用变基而非合并进行拉取
# 推送
git push origin feature/login
git push -u origin feature/login # 设置上游(-u)以便后续 git push
git push --force-with-lease # 比 --force 更安全的替代方案
合并与变基
# 将分支合并到当前分支
git merge feature/login
git merge --no-ff feature/login # 始终创建合并提交
# 将当前分支变基到 main
git rebase main
git rebase -i HEAD~3 # 交互式变基最近 3 次提交
# 如果冲突过于复杂,中止变基
git rebase --abort
贮藏
# 临时保存工作进度
git stash
git stash push -m "WIP: half-done feature"
# 列出贮藏
git stash list
# 应用最近的贮藏
git stash pop # 应用并从贮藏中移除
git stash apply # 应用但保留在贮藏中
# 应用特定贮藏
git stash apply stash@{2}
# 删除贮藏
git stash drop stash@{0}
git stash clear # 移除所有贮藏
撤销更改
# 丢弃工作目录更改(未暂存)
git restore file.txt # 现代方式
git checkout -- file.txt # 传统方式
# 取消暂存文件(保留工作目录中的更改)
git restore --staged file.txt
# 撤销上次提交(保留更改在暂存区)
git reset --soft HEAD~1
# 撤销上次提交(保留更改未暂存)
git reset HEAD~1
# 撤销上次提交(完全丢弃更改)
git reset --hard HEAD~1
# 还原提交(创建一个新提交来撤销更改)
git revert abc1234 # 对共享历史安全
-> 试试 Git 备忘录参考