Git实用技巧

Git 官方文档: https://git-scm.com/docs

一、基本操作

1. 新建 git 仓库

1
git init

1
git init -b main
1
git config --global init.defaultBranch main
1
git branch -m main

2. 克隆远程仓库

1
git clone http://git.example.com/someone/test.git
1
git clone http://git.example.com/someone/test.git test
1
git clone http://git.example.com/someone/test.git --depth=1 -b main

3. 提交代码

1
git add -a
1
git add -u
1
git add .
1
git commit
1
git commit -m "first commit"
1
git commit -am "first commit"

4. 查看仓库状态

1
git status

1
git status -s

5. 查看提交历史

https://git-scm.com/docs/git-log

1
git log

6. 新建分支

1
git branch test
1
git checkout test
1
git checkout -b test

7. 合并分支

1
2
git checkout main
git merge test

8. 删除分支

1
git branch -d test-not-need

9. 合并冲突

当两个分支都对同一行进行了修改,git 便会产生冲突,并标记为未合并

此时将每个文件进行修改,确认最后的内容,使用 git add 方法标记为冲突已解决

1
git add .\A.txt

在所有文件的冲突均已解决后,使用 commit 提交此次修改。

1
git merge --abort

10. 远程仓库

1
git remote

默认应该为空

1
git remote add origin http://git.example.com/someone/test.git
1
git push origin main
1
git fetch --all
1
git fetch origin
1
2
git branch --set-upstream-to=origin/main main
git branch -u origin/main main

1
git push -u origin main
1
git pull
1
git pull origin main

二、常见技巧

1. 临时保存成果

1
git stash

1
git stash pop

2. 合并分支灵活选择 rebase/merge

1
git merge test
1
git rebase test

3. cherry-pick

适合 hotfix

1
git cherry-pick 12d654f1d701cbf7cd9abb98ce84eeef460a24a7

4. 修改上次提交

1
git commit --amend

会同时提交暂存的文件

5. 取消文件修改

1
git checkout .\C.txt

6. 弃用提交

1
2
3
4
5
# 保留文件
git reset --soft 12d654f1d701cbf7cd9abb98ce84eeef460a24a7

# 丢弃修改
git reset --hard 12d654f1d701cbf7cd9abb98ce84eeef460a24a7

7. 补丁文件

1
2
git diff [file] > a.patch
git apply a.patch