Git 核心概念:工作区与暂缓区(添加提交及查看状态充分体现)

前言

首先,我们要先知道什么是 工作区(Working Directory) 和 暂缓区(Postponed Zone)。

工作区(Working Directory):

顾名思义,工作的地区。我们电脑中每个项目目录就是一个工作区。
在这里插入图片描述
暂缓区(Postponed Zone):

暂缓区在哪里?我们工作区中 .git 这个隐藏目录就是我们的暂缓区

Git 和其他版本控制系统(SVN)不同之处就是有暂存区的概念。不权威的说,暂缓区就是一个我们常说的 Git 版本库或 Git 仓库。Git 的版本库里存了很多东西,其中最重要的就是称为 stage 的暂存区,还有 Git 为我们自动创建的第一个分支 master,以及指向 master 的一个指针 HEAD

添加提交(充分体现核心概念)

回顾一下过程:工作区 >>>> 暂存区 >>>> 仓库

当我新建 Git 版本库时,Git 自动创建了 master 分支。当我 git commit 时肯定往 master 分支上提交的更改,这毫无疑问。
在这里插入图片描述
一、在工作区中新建一个 test.txt 文件,紧接着 git status 查看状态:

$ touch test.txt
$ git status
On branch master
nothing to commit, working tree clean

从结果来看,第一行 On branch master 提示我们处于哪个分支,目前处于 master。第二行 nothing to commit, working tree clean 表示我们目前没有任何的提交操作。

二、在 test.txt 文件中新增一段内容,紧接着 git status 查看状态:

$ vim test.txt
$ 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: test.txt
no changes added to commit (use "git add" and/or "git commit -a")

从结果来看,第一句还是提示我们处在哪个分支。第二行表示我们已经有了操作,第五行已经给出提示,而这个操作就发生在 test.txt 文件,最后一行提示 我们 没有要添加提交的更改,Git 一直监视这工作区文件的修改,接下来我们添加提交。

三、将 test.txt 添加提交到暂缓区,紧接着 git status 查看状态:

$ git add test.txt
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
  	  modified: test.txt

从结果来看,modified:test.txt 从红色变为绿色字体,这表示改动的文件已经放入暂缓区,此时文件是 “安全” 的,下图表示了 test.txt 文件的所在位置:
在这里插入图片描述
在暂缓区中,test.txt 能被拿出来吗?能!

四、从暂缓区中移除 test.txt 文件,紧接着 git status 查看状态:

$ git rm --cached test.txt
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
 		deleted: test.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
 		test.txt

从结果上不难看出,test.txt 文件已被 Git 列为不跟踪的文件了。

五、把暂缓区的所有文件提交到当前分支 master

注意,如果你是跟着本文一步步做的,那么执行以下命令前,先执行 git addtest.txt 添加到暂存区,因为第四步我们给从暂缓区移除了。

$ git commit -m "This is a demo!"
[master d5cbf24] This is a demo!
 1 file changed, 1 insertion(+)

从结果可以看到,Git 完成了提交,并提示我们一些信息。

此时 test.txt 就跑到了 master 分支:
在这里插入图片描述
以上便是 工作区 >>>> 暂存区 >>>> 仓库 整个过程。

注意事项

每次 git commit 提交后,你又没有对工作区做任何修改的话,此时暂缓区是 干净 的:

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

也就是这个样子:
在这里插入图片描述

写在后面

以下简单明了的分析来自 九只蜗牛Leo 分享:

Git管理的文件分为:工作区,版本库,版本库又分为暂存区stage和暂存区分支master(仓库)
git add把文件从工作区>>>>暂存区,git commit把文件从暂存区>>>>仓库,
git diff查看工作区和暂存区差异,
git diff --cached查看暂存区和仓库差异,
git diff HEAD 查看工作区和仓库的差异,
git add的反向命令git checkout,撤销工作区修改,即把暂存区最新版本转移到工作区,
git commit的反向命令git reset HEAD,就是把仓库最新版本转移到暂存区。

发布了242 篇原创文章 · 获赞 366 · 访问量 78万+

猜你喜欢

转载自blog.csdn.net/weixin_44198965/article/details/104100017