1. 程式人生 > 實用技巧 >3. Git如何管理修改

3. 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提交修改,通過git status檢視工作區狀態:

$ 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 8c299f0] 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 db28b2c..9a8b341 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.
\ No newline at end of file
+Git tracks changes of files.
\ No newline at end of file

可見,第二次修改確實沒有被提交。

小結

每次修改,如果不用git add到暫存區,那就不會加入到commit中。