1. 程式人生 > 實用技巧 >Git 5. 工作區和暫存區

Git 5. 工作區和暫存區

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

先來看名詞解釋。

工作區(Working Directory)

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

版本庫(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.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 e43a48b] understand how stage works
 2 files changed, 2 insertions(+)
 create mode 100644 LICENSE

一旦提交後,如果你又沒有對工作區做任何修改,那麼工作區就是“乾淨”的:

$ git status
On branch master
nothing to commit, working tree clean

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

原文:https://www.liaoxuefeng.com/wiki/896043488029600/897271968352576