Git和其他版本控制系統如SVN的一個不同之處就是有暫存區的概念。
先來看名詞解釋。
工作區(Working Directory):就是你在電腦裏能看到的目錄,比如我的learngit文件夾就是一個工作區:
版本庫(Repository):工作區有一個隱藏目錄“.git”,這個不算工作區,而是Git的版本庫。
Git的版本庫裏存了很多東西,其中最重要的就是稱爲stage(或者叫index)的暫存區,還有Git爲我們自動創建的第一個分支master,以及指向master的一個指針叫HEAD。
分支和HEAD的概念我們以後再講。
前面講了我們把文件往Git版本庫裏添加的時候,是分兩步執行的:
第一步是用“git add”把文件添加進去,實際上就是把文件修改添加到暫存區;
第二步是用“git commit”提交更改,實際上就是把暫存區的所有內容提交到當前分支。
因爲我們創建Git版本庫時,Git自動爲我們創建了唯一一個master分支,所以,現在,commit就是往master分支上提交更改。
簡單理解爲,需要提交的文件修改通通放到暫存區,然後,一次性提交暫存區的所有修改。
俗話說,實踐出真知。先對readme.txt做個修改,比如加上一行內容:
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
然後,在工作區新增一個LICENSE文本文件(內容隨便寫)。
先用git status查看一下狀態:
$ 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
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# LICENSE
no changes added to commit (use "git add" and/or "git commit -a")
Git非常清楚地告訴我們,readme.txt被修改了,而LICENSE還從來沒有被添加過,所以它的狀態是Untracked。
現在,使用兩次命令git add,把readme.txt和LICENSE都添加後,用git status再查看一下:
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: LICENSE
# modified: readme.txt
#
現在,暫存區的狀態就變成這樣了:
所以,git add命令實際上就是把要提交的所有修改放到暫存區(Stage),然後,執行git commit就可以一次性把暫存區的所有修改提交到分支。
$ git commit -m "understand how stage works"
[master 27c9860] understand how stage works
2 files changed, 675 insertions(+)
create mode 100644 LICENSE
一旦提交後,如果你又沒有對工作區做任何修改,那麼工作區就是“乾淨”的:
$ git status
# On branch master
nothing to commit (working directory clean)
現在版本庫變成了這樣,暫存區就沒有任何內容了:
小結
暫存區是Git非常重要的概念,弄明白了暫存區,就弄明白了Git的很多操作到底幹了什麼。