教程
https://learngitbranching.js.org/
https://backlog.com/git-tutorial/cn/stepup/stepup7_1.html
基本命令
git clone ……
git add README.md
git commit -m "add README"
git push
原理
- 1.把 work dir 中的修改加入 stage
git add .
- 2.把 stage 中的修改还原到 work dir 中
在 work dir 做出的「修改」会被 stage 覆盖,无法恢复
这里撤销的只是修改,新增的文件不会被撤销
git checkout a.txt
- 3.将 stage 区的文件添加到 history 区
git commit -m '一些描述'
git commit --amend # amend把修改和之前的那个 commit 中的修改合并,作为一个 commit 提交到 history 区
- 4.将 history 区的文件还原到 stage 区
不会改变 work dir 中的数据,会改变 stage 区的数据,所以应确保 stage 中被改动数据是可以抛弃的。
git reset a.txt
git reset --mixed HEAD a.txt
# 不改变 work dir 中的任何数据,
# 将 stage 区域中的 a.txt 文件还原成 HEAD 指向的 commit history 中的样子。
# 就相当于把对 a.txt 的修改从 stage 区撤销,但依然保存在 work dir 中,变为 unstage 的状态。
- 5.将 work dir 的修改提交到 history 区
先 git add 然后 git commit
git commit -a # 快捷方法
- 6.将 history 区的历史提交还原到 work dir 中
这里撤销的也只是修改,新增的文件不会被撤销
将指定文件在 work dir 的数据恢复成指定 commit 的样子,且会删除该文件在 stage 中的数据,都无法恢复
git checkout HEAD .
# work dir 和 stage 中所有的「修改」都会被撤销,
# 恢复成 HEAD 指向的那个 history commit
-
- 合并多个 commit
$ git reset 17bd20c
$ git add .
$ git commit -m 'balabala'
# 相当于把 HEAD 移到了 17bd20c 这个 commit,而且不会修改 work dir 中的数据,所以只要 add 再 commit,
# 就相当于把中间的多个 commit 合并到一个了。
- 由于 HEAD 指针的回退,导致有的 commit 在 git log 命令中无法看到,怎么得到它们的 Hash 值呢?
git reflog
分支
创建分支
git branch (branchname)
切换分支
git checkout (branchname)
git checkout -b (branchname) # 创建新分支并立即切换到该分支下
显示分支
git branch
删除分支
git branch -d (branchname)
分支合并
(A)git merge B 把B合并进A
#修改冲突的文件内容,重新提交。
git add .
git commit -m ""
(A)git rebase B 把A合并进B
#修改冲突的文件内容,重新提交。
$ git add myfile.txt
$ git rebase --continue
# 取消rebase,指定 --abort选项
切换分支
git log
git checkout HEAD^
git checkout HEAD~2
移动分支commit
git branch -f master HEAD~3 # 移动master到HEAD~3
git revert # 创建一个新commit head前进
git reset (HEAD^) # head回退
git cherry-pick Y # 将Y commit添加到当前分支
改写提交的历史记录
git rebase -i HEAD~4 # 要改变倒数第4次后的提交
汇合分支上的提交,然后一同合并到分支
git merge --squash issue1