現在,假定你已經完全掌握了暫存區的概念。下面,我們要討論的就是,爲什麼Git比其他版本控制系統設計得優秀,因爲Git跟蹤並管理的是修改,而非文件。你會問,什麼是修改?比如你新增了一行,這就是一個修改,刪除了一行,也是一個修改,更改了某些字符,也是一個修改,刪了一些又加了一些,也是一個修改,甚至創建一個新文件,也算一個修改。
爲什麼說Git管理的是修改,而不是文件呢?我們還是做實驗。
第一步,對ReadMe.txt做一個修改,比如加一行內容:
$ cat ReadMe.txt
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
Git tracks changes.
然後,添加:
$ git add ReadMe.txt
Administrator@WTI32F0K1TGTCP3 MINGW64 /d/Git (master)
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: ReadMe.txt
然後,再修改ReadMe.txt:
$ cat ReadMe.txt
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
Git tracks changes of files.
提交:
$ git commit -m "git tracks changes"
[master fb315a3] git tracks changes
1 file changed, 1 insertion(+)
提交後,再看看狀態:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: ReadMe.txt
no changes added to commit (use "git add" and/or "git commit -a")
咦,怎麼第二次的修改沒有被提交?別激動,我們回顧一下操作過程:
第一次修改 -> git add
-> 第二次修改 -> git commit
你看,我們前面講了,Git管理的是修改,當你用git add
命令後,在工作區的第一次修改被放入暫存區,準備提交,但是,在工作區的第二次修改並沒有放入暫存區,所以,git commit
只負責把暫存區的修改提交了,也就是第一次的修改被提交了,第二次的修改不會被提交。
提交後,用git diff HEAD -- ReadMe.txt
命令可以查看工作區和版本庫裏面最新版本的區別:
$ git diff HEAD -- ReadMe.txt
diff --git a/ReadMe.txt b/ReadMe.txt
index 76d770f..a9c5755 100644
--- a/ReadMe.txt
+++ b/ReadMe.txt
@@ -1,4 +1,4 @@
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
-Git tracks changes.
+Git tracks changes of files.
可見,第二次修改確實沒有被提交。
那怎麼提交第二次修改呢?你可以繼續git add
再git commit
,也可以彆着急提交第一次修改,先git add
第二次修改,再git commit
,就相當於把兩次修改合併後一塊提交了:
第一次修改 -> git add
-> 第二次修改 -> git add
-> git commit
好,現在,把第二次修改提交了。
小結
現在,你又理解了Git是如何跟蹤修改的,每次修改,如果不用git add
到暫存區,那就不會加入到commit
中。