这是我参与「第五届青训营 」伴学笔记创作活动的第 7 天
只提交文件的部分内容
假设我们当前是下面这个状态
$ git log --oneline
8c7e150 (HEAD -> master) cmt 6
280fc06 cmt 5
e353c79 cmt 4
4b6168e (cat) cmt 3
4e4acae commit 2
ed641db commit 1
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: tmp.txt
no changes added to commit (use "git add" and/or "git commit -a")
$ cat tmp.txt
line 1
line 2
line 3
line 4
line 5
line 6
sercert 1
sercert 2
sercert 3
line 7
我想 commit 一个 cmt 7 但是我只想把 line 7 提交上去,那三行 sercert 我不想提交,这时候要怎么做呢?
输入 git add -p tmp.txt,git 就会询问是否将这个区域加到暂存区
$ git add -p .
diff --git a/tmp.txt b/tmp.txt
index f985857..c24d9f7 100644
--- a/tmp.txt
+++ b/tmp.txt
@@ -4,3 +4,7 @@ line 3
line 4
line 5
line 6
+sercert 1
+sercert 2
+sercert 3
+line 7
(1/1) Stage this hunk [y,n,q,a,d,e,?]?
发现有很多选项,我们来看看有什么选项
# y 暂存当前区域
y - stage this hunk
# n 不暂存当前区域
n - do not stage this hunk
# q 退出,不暂存这个区域和之后的所有区域
q - quit; do not stage this hunk or any of the remaining ones
# a 暂存当前区域和之后的这个文件的所有区域
a - stage this hunk and all later hunks in the file
# d 不暂存当前区域和之后的这个文件的所有区域
d - do not stage this hunk or any of the later hunks in the file
# e 手动编辑当前区域
e - manually edit the current hunk
? - print help
我们要自定义那就回答 e
1 # Manual hunk edit mode -- see bottom for a quick guide.
2 @@ -4,3 +4,7 @@ line 3
3 line 4
4 line 5
5 line 6
6 +sercert 1
7 +sercert 2
8 +sercert 3
9 +line 7
10 # ---
11 # To remove '-' lines, make them ' ' lines (context).
12 # To remove '+' lines, delete them.
13 # Lines starting with # will be removed.
14 # If the patch applies cleanly, the edited hunk will immediatel y be marked for staging.
15 # If it does not apply cleanly, you will be given an opportunit y to
16 # edit again. If all lines of the hunk are removed, then the e dit is
17 # aborted and the hunk is left unchanged.
跳出 vim 编辑器,可以看到说明,如果我们不想要那些修改,就把那几行删掉,我们删掉 6 - 8 行
1 # Manual hunk edit mode -- see bottom for a quick guide.
2 @@ -4,3 +4,7 @@ line 3
3 line 4
4 line 5
5 line 6
6 +line 7
7 # ---
8 # To remove '-' lines, make them ' ' lines (context).
9 # To remove '+' lines, delete them.
10 # Lines starting with # will be removed.
11 # If the patch applies cleanly, the edited hunk will immediatel y be marked for staging.
12 # If it does not apply cleanly, you will be given an opportunit y to
13 # edit again. If all lines of the hunk are removed, then the e dit is
14 # aborted and the hunk is left unchanged.
保存退出之后,我们来看一下 git status
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: tmp.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: tmp.txt
看到只添加了一部分的修改内容,还有一部分修改没有添加到暂存区,这样我们就可以先 git commit 一部分了