Git学习(六)--工作区和暂存区

转载廖雪峰的官方网站

工作区(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进行修改,比如添加一行

1
2
3
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.

​ 然后在添加一个文件LICENSE文本文件

1
apache license

​ 先使用git status查看状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ 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查看一下状态.

1
2
3
4
5
6
7
8
$ git add .
$ 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就可以一次性把暂存区所有的修改提交到分支。

1
2
3
4
$ git commit -m "understand how stage works"
[master eb1b3cd] understand how stage works
2 files changed, 2 insertions(+)
create mode 100644 LICENSE

一旦提交后,如果没有对工作区做任何修改,那么工作区就是干净的。

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

现在版本库就变为

小结

暂存区是Git非常重要的概念,弄明白了暂存区,就弄明白了Git的很多操作到底干了什么。

没弄明白暂存区是怎么回事的童鞋,请向上滚动页面,再看一次。