Git常用命令

一、基础配置

git config --global user.name "Your Name"
git config --global user.email "your@example.com"
git config --global core.editor "code --wait"   # 默认编辑器
git config --list                                # 查看配置

二、仓库创建与克隆

git init                                   # 初始化仓库
git clone <url>                            # 克隆
git clone -b <branch> <url>                # 克隆指定分支
git clone <url> <dir>                      # 克隆到指定目录

三、基本工作流

git status        # 查看状态
git add <file>    # 暂存(git add . 暂存全部)
git commit -m "msg"      # 提交
git commit -a -m "msg"   # 暂存已跟踪文件并提交(不含未跟踪文件)

四、分支管理

git branch                  # 列出分支
git branch <name>           # 创建
git checkout <name>         # 切换(新版本也支持 git switch)
git checkout -b <name>      # 创建并切换
git branch -d <name>        # 删除已合并分支
git branch -D <name>        # 强制删除未合并分支
git branch -m <new>         # 重命名当前分支

五、远程仓库

git remote -v
git remote add <name> <url>
git fetch <remote>           # 拉取不合并
git pull <remote> <branch>   # 拉取并合并
git push -u <remote> <branch>  # 推送并设置上游

六、撤销与回退

git checkout -- <file>      # 丢弃工作区修改
git reset HEAD <file>       # 撤销暂存(保留修改)
git commit --amend          # 修改最后一次提交(未推送时)
git reset <hash>            # 回退提交(保留更改)
git reset --hard <hash>     # 回退并丢弃更改(⚠️ 慎用,先看 reflog)
git push -f                 # 强制推送(⚠️ 覆盖远端历史,谨慎)

七、日志

git log
git log --oneline
git log --graph --oneline --all
git log -p <file>           # 文件修改历史
git log --author="name"
git log --grep="keyword"
git log --stat              # 变更统计

八、标签

git tag                          # 列出
git tag <name>                   # 轻量标签
git tag -a <name> -m "msg"       # 含注释标签
git push <remote> <tag>          # 推送单个
git push <remote> --tags         # 推送全部
git tag -d <name>                # 删本地
git push <remote> :refs/tags/<name>  # 删远程

九、stash 与 rebase

git stash            # 暂存当前修改
git stash list
git stash pop        # 恢复最近
git stash apply stash@{n}
git stash drop stash@{n}

git rebase <branch>          # 变基
git rebase -i <hash>         # 交互式变基(整理提交)

十、差异比较

git diff                  # 工作区 vs 暂存区
git diff --cached         # 暂存区 vs 最近提交
git diff HEAD             # 工作区 vs 最近提交
git diff <c1> <c2>         # 两个提交间差异
git diff --stat

十一、cherry-pick

git checkout main
git cherry-pick <hash>            # 把提交搬到当前分支
git cherry-pick <c1> <c2>         # 多个提交
git cherry-pick -n <hash>         # 只应用不提交
git cherry-pick <start>..<end>    # 范围(不含 start)
git cherry-pick <start>^..<end>   # 范围(含 start)

实战体会

固定分支工作流比记住一百个命令更重要。我的个人规范:master 永远保持可发布状态;功能开发开分支,开发完 rebase 到最新 master 再合并,保证提交历史是干净的线性图;每天 git pull --rebase,避免无意义的 merge 提交。

cherry-pick 是修 hotfix 的救命工具。线上出问题、而修复已经在另一个分支里时,git cherry-pick 把单个提交搬过去比手动重打一遍可靠得多。配合 git stash 处理”改到一半要切分支”的场景,日常开发基本不会卡壳。

reflog 是后悔药。有过 git reset --hard 手滑的经历之后,我养成了习惯:reset/checkout 前心里过一遍 reflog 在哪,真出错了 git reflog + git reset --hard HEAD@{n} 能找回一切。

把常用命令配成 alias。提交规范(feat:/fix: 前缀)、git lg 看美化日志、git st 快捷状态——alias 一次配置,长期省时间。

滚动至顶部