引言
Git是最流行的版本控制系统。本文介绍Git的核心命令和实战技巧。
一、基础命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| git init
git clone https://github.com/user/repo.git
git status
git add file.txt git add .
git commit -m "commit message"
git log git log --oneline --graph
git diff git diff HEAD
|
二、分支管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| git branch feature
git checkout feature git switch feature
git checkout -b feature git switch -c feature
git branch git branch -a
git checkout main git merge feature
git branch -d feature git branch -D feature
|
三、远程操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| git remote -v
git remote add origin https://github.com/user/repo.git
git pull origin main
git push origin main
git push -u origin feature
git push origin --delete feature
|
四、撤销操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| git checkout -- file.txt git restore file.txt
git reset HEAD file.txt git restore --staged file.txt
git reset --soft HEAD^ git reset --mixed HEAD^ git reset --hard HEAD^
git reset --hard commit_id
git revert commit_id
|
五、冲突解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| git merge feature
git status
git add file.txt
git commit -m "Merge feature branch"
|
六、工作流
6.1 Git Flow
1 2 3 4 5 6 7 8
| main/master develop
feature/* release/* hotfix/*
|
6.2 GitHub Flow
1 2 3 4 5 6
| 1. 从main创建分支 2. 提交更改 3. 创建Pull Request 4. 代码审查 5. 合并到main 6. 部署
|
七、高级技巧
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| git stash git stash list git stash pop git stash apply
git rebase main git rebase -i HEAD~3
git cherry-pick commit_id
git tag v1.0.0 git push origin v1.0.0
git submodule add https://github.com/user/repo.git git submodule update --init
|
总结
Git核心:
- 基础命令:add、commit、push、pull
- 分支管理:创建、切换、合并
- 冲突解决:识别和处理冲突
- 工作流:团队协作规范
参考资料