Git 常用操作指南
本文整理了 Git 日常开发中的常用指令,分为常规操作与进阶用法两部分,涵盖分支管理、代码同步、版本回退、子模块管理等核心场景。
一、常规操作
1. 基础配置
1 2 3 4 5 6 7 8 9 10 11 12
| git config --list
git config --global user.name "Your Name" git config --global user.email "email@example.com"
git config --global alias.co checkout git config --global alias.ci commit git config --global alias.br branch git config --global alias.st status
|
2. 分支管理 (Branch)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| git branch
git branch -a
git branch <branch-name>
git checkout <branch-name>
git switch <branch-name>
git checkout -b <branch-name>
git branch -d <branch-name> git branch -D <branch-name>
git branch | grep 'qa' | xargs git branch -d
git push origin --delete <branch-name>
|
3. 代码提交与同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| git status
git add .
git commit -m "commit message"
git pull origin <branch-name>
git push origin <branch-name>
|
4. 标签管理 (Tag)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| git tag
git ls-remote --tags
git tag v1.0.0
git tag v1.0.0 <commit-id> -m "Release v1.0.0"
git push origin v1.0.0 git push origin --tags
git tag -d v1.0.0
git push origin :refs/tags/v1.0.0
git push origin --delete v1.0.0
|
二、进阶用法
1. 跨分支代码同步 (Cherry Pick)
将其他分支的某次提交应用到当前分支。
1 2 3 4 5 6 7 8 9
| git checkout master
git cherry-pick <commit-id>
git add . git cherry-pick --continue
|
2. 版本回退与撤销
撤销工作区修改
1 2 3 4
| git checkout -- <file>
git restore <file>
|
修改最近一次提交 (Amending)
1 2 3
| git add . git commit --amend
|
版本回退 (Reset)
1 2 3 4 5 6 7 8 9 10
| git reset --soft HEAD^
git reset HEAD^
git reset --hard HEAD^
git reset --hard <commit-id>
|
无痕删除中间的 commit (Rebase)
1 2 3 4 5 6
| git rebase -i HEAD~3
git push origin <branch-name> --force
|
3. .gitignore 更新
当 .gitignore 规则更新后,已被 Git 追踪的文件不会自动被忽略,需要清除缓存。
1 2 3 4 5 6 7 8
| git rm -r --cached .
git add .
git commit -m "Refresh .gitignore"
|
4. 子模块管理 (Submodule)
添加子模块
1
| git submodule add <repository-url> <path>
|
克隆含子模块的项目
1 2 3 4 5
| git clone --recurse-submodules <repository-url>
git submodule update --init --recursive
|
更新子模块
1
| git submodule update --remote
|
删除子模块
1 2 3 4 5 6 7
| git rm <submodule-path>
rm -rf .git/modules/<submodule-path>
|
5. 远程仓库同步 (Sync Fork)
当需要同步上游仓库 (upstream) 的代码时:
1 2 3 4 5 6 7 8
| git remote add upstream <upstream-url>
git fetch upstream
git merge upstream/master
|
三、常见问题 (Q&A)
Q1: 报错 Error: spawn git ENOENT
通常是因为 Git 环境变量未配置或 VSCode 配置路径错误。
检查 VSCode settings.json:
1
| "git.path": "/usr/bin/git"
|
Q2: 如何清理无效的远程分支引用?
1
| git rm --cache ./public/env.config.js
|