外观
Git 常用命令
基础配置
bash
git config --global user.name "你的名字"
git config --global user.email "你的邮箱"
git config --global core.editor "vim" # 设置默认编辑器
git config --global color.ui true # 开启颜色显示
git config --list # 查看所有配置仓库操作
bash
git init # 初始化本地仓库
git clone <url> # 克隆远程仓库
git clone <url> <dir> # 克隆到指定目录暂存与提交
bash
git status # 查看当前状态
git status -s # 简洁状态输出
git add <file> # 暂存单个文件
git add . # 暂存所有改动
git add -A # 暂存所有改动(包括删除)
git commit -m "提交信息" # 提交暂存区
git commit -am "提交信息" # 跳过暂存,直接提交已跟踪文件
git commit --amend # 修改上次提交(不要用于已推送的提交)分支管理
bash
git branch # 查看本地分支
git branch -a # 查看所有分支(含远程)
git branch -r # 查看远程分支
git branch <name> # 创建分支
git checkout <name> # 切换分支
git checkout -b <name> # 创建并切换分支
git merge <branch> # 合并指定分支到当前分支
git rebase <branch> # 变基到指定分支
git branch -d <name> # 删除分支(已合并)
git branch -D <name> # 强制删除分支(未合并)
git push origin <branch> # 推送分支到远程
git push origin --delete <branch> # 删除远程分支远程仓库
bash
git remote # 查看远程仓库
git remote -v # 查看远程仓库详细信息
git remote add origin <url> # 添加远程仓库
git remote set-url origin <url> # 修改远程仓库地址
git fetch # 获取远程更新(不合并)
git pull # 获取并合并远程更新
git pull --rebase # 获取并变基
git push origin <branch> # 推送到远程分支
git push -u origin <branch> # 推送并设置上游关联
git push --force # 强制推送(慎用)查看历史
bash
git log # 查看提交历史
git log --oneline # 简洁显示(每行一条)
git log --oneline -n 10 # 最近 10 条
git log --graph # 图形化显示分支
git log --all # 查看所有分支历史
git show <commit> # 查看指定提交详情
git show <commit>:<file> # 查看指定提交中的文件内容
git blame <file> # 查看文件每行的修改记录撤销操作
bash
git checkout -- <file> # 撤销工作区修改(危险!)
git restore <file> # 撤销工作区修改(Git 2.23+)
git reset HEAD <file> # 取消暂存
git restore --staged <file> # 取消暂存(Git 2.23+)
git reset --hard <commit> # 重置到指定提交(危险!)
git reset --soft <commit> # 重置到指定提交,保留工作区
git revert <commit> # 撤销指定提交(创建新提交)标签
bash
git tag # 查看标签
git tag <name> # 创建轻量标签
git tag -a <name> -m "标签信息" # 创建附注标签
git tag -a <name> <commit> # 为指定提交创建标签
git push origin <tag> # 推送标签到远程
git push origin --tags # 推送所有标签
git checkout <tag> # 切换到标签
git tag -d <name> # 删除本地标签
git push origin --delete <tag> # 删除远程标签暂存
bash
git stash # 暂存工作区
git stash list # 查看暂存列表
git stash pop # 恢复最近暂存并删除
git stash apply # 恢复最近暂存(保留)
git stash drop # 删除最近暂存
git stash clear # 清空所有暂存工作流
常用工作流程
bash
# 创建特性分支
git checkout -b feature/xxx
# 开发完成后合并到主分支
git checkout main
git pull origin main
git merge feature/xxx
# 推送到远程
git push origin main
# 删除本地分支
git branch -d feature/xxx冲突解决
bash
git status # 查看冲突文件
# 手动编辑冲突文件,删除 <<<<<<<、=======、>>>>>>> 标记
git add <file> # 标记冲突已解决
git commit # 完成合并其他
bash
git diff # 查看工作区与暂存区差异
git diff --cached # 查看暂存区与上次提交差异
git diff <commit1> <commit2> # 查看两次提交差异
git clean -n # 预览未跟踪文件(不删除)
git clean -f # 删除未跟踪文件
git clean -df # 删除未跟踪文件和目录
git gc # 清理无用对象
git prune # 清理丢失的对象