git知識總結3——工作區和暫存區
Git和其他版本控制系統如SVN的一個不同之處就是有暫存區的概念。
先來看名詞解釋。
版本庫(Repository)
工作區有一個隱藏目錄.git
,這個不算工作區,而是Git的版本庫。
Git的版本庫裡存了很多東西,其中最重要的就是稱為stage(或者叫index)的暫存區,還有Git為我們自動建立的第一個分支master
,以及指向master
的一個指標叫HEAD
。
分支和HEAD
的概念我們以後再講。
前面講了我們把檔案往Git版本庫裡新增的時候,是分兩步執行的:
第一步是用git add
把檔案新增進去,實際上就是把檔案修改新增到暫存區;
第二步是用git commit
因為我們建立Git版本庫時,Git自動為我們建立了唯一一個master
分支,所以,現在,git 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的很多操作到底幹了什麼。
沒弄明白暫存區是怎麼回事的童鞋,請向上滾動頁面,再看一次。