1. 程式人生 > >工作區和暫存區

工作區和暫存區

res 文本 reset osi master 更改 所有 系統 解釋

Git和其他版本控制系統如SVN的一個不同之處就是有暫存區的概念。

先來看名詞解釋。

工作區(Working Directory)

就是你在電腦裏能看到的目錄,比如我的learngit文件夾就是一個工作區:

技術分享

版本庫(Repository)

工作區有一個隱藏目錄.git,這個不算工作區,而是Git的版本庫。

Git的版本庫裏存了很多東西,其中最重要的就是稱為stage(或者叫index)的暫存區,還有Git為我們自動創建的第一個分支master,以及指向master的一個指針叫HEAD

技術分享

前面講了我們把文件往Git版本庫裏添加的時候,是分兩步執行的:

第一步是用git add把文件添加進去,實際上就是把文件修改添加到暫存區;

第二步是用git commit提交更改,實際上就是把暫存區的所有內容提交到當前分支。

因為我們創建Git版本庫時,Git自動為我們創建了唯一一個master分支,所以,現在,git commit就是往master分支上提交更改。

你可以簡單理解為,需要提交的文件修改通通放到暫存區,然後,一次性提交暫存區的所有修改。

俗話說,實踐出真知。現在,我們再練習一遍,先對readme.txt做個修改,比如加上一行內容:

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.txtLICENSE都添加後,用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)

現在版本庫變成了這樣,暫存區就沒有任何內容了:

技術分享

工作區和暫存區