文章目录
概述
git是大名鼎鼎的版本控制工具,会将文件的每次更新都完整地记录下来,从而让用户退回到任何一个版本。而在项目推进的过程中,文件在Git中存在三种状态
- 已提交(committed):已经被安全地保存在本地数据库中。
- 已修改(modified):已修改但还没保存。
- 已暂存(staged):被修改的文件已经放在了下次提交时要保存的清单中。
这三种状态,对应三个目录/文件,分别是
- 本地数据目录:即项目中那个名为git的默认隐藏的文件夹,这里保存着元数据和对象数据库。
- 工作目录:从项目中取出某个版本的所有文件和目录
- 暂存区域:一般是git文件夹中的某个文件,也叫索引文件。
本地数据目录
为了理解这三种状态和这三个目录,下面做一个简单的演示。
首先,新建一个文件夹,并通过init命令,初始化仓库。从而生成.git目录,这个git目录就是本地数据目录。
bash
mkdir demo
cd demo
git init
dir /A:H
...
2025/12/02 09:46 <DIR> .git
Untracked
然后,在demo下面新建一个hello.txt文件,内容随便写,比如写个hello。此时,hello.txt位于工作目录,状态则是Untracked,且最后一行提示用git add来track。之所以会出现这种情况,是因为hello.txt尚未被Git追踪过,理论上尚未进入Git的管辖范围。
bash
git status
...
Untracked files:
(use "git add <file>..." to include in what will be committed)
hello.txt
nothing added to commit but untracked files present (use "git add" to track)
暂存区域
按照提示,将hello.txt加入到git,此时再去查看其状态,则出现了Changes to be committed,即将被提交,标明此时的状态是已暂存。括号中的提示是,使用某某指令以取消暂存(unstage),也同样说明了当前的状态是已暂存。
bash
git add hello.txt
git status
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: hello.txt
提交
【commit】指令即可将暂存的文件提交到本地数据库
bash
git commit -m "first commit"
[master (root-commit) c54d388] first commit
1 file changed, 1 insertion(+)
create mode 100644 hello.txt
git status
On branch master
nothing to commit, working tree clean
其中,【-m】后面是一些备注信息,随便写。其反馈信息中,给出了hello.txt的权限模式为100644,这种记法与Linix中的文件权限位类似,100表示普通文件,644表示权限是6(rw-)、4(r--)、4(r--)。
而此时的状态则是没有文件需要commit,即所有文件都处于已提交的状态。
已修改
此时,我们将hello.txt的内容修改为Hello World,然后再去查看状态,则hello.txt不出意料地变成了modified。
bash
git status
...
(use "git restore <file>..." to discard changes in working directory)
modified: hello.txt
...
接下来再去add并commit,其状态就又变成提交了。
bash
git add hello.txt
git commit -m "second commit"
对比文件变化
【git diff】可以对比文本差异,【HEAD~N】表示前N版的内容。当前版本与上一个版本的差异如下所示,可见diff默认是按行来对比差异的。即减掉了hello这一行,新增了hello world这一行。
bash
git diff HEAD~1
diff --git a/hello.txt b/hello.txt
index b6fc4c6..3b18e51 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-hello
\ No newline at end of file
+hello world
滚回到上一个版本
【reset】指令可以重置版本,下面的指令,可以将工作目录滚回到上一个版本,这时打开hello.txt,里面的内容仅剩下hello了。
git reset --hard HEAD~1
接下来故技重施,在hello.txt下面新增一行world,然后再去commit,其中【-a】表示先add,再commit,可以省略add这一步。然后通过【log】指令,查看当前所有的版本,发现"second commit"已经不见了。但是如果用【reflog】,就会重新看到。reflog默认保存90天,如果这90天之内,不再提起second commit,那么它将永远消失。
bash
git commit -a -m "3rd"
git log --oneline
856cbac (HEAD -> master) 3rd
c54d388 first commit
git reflog
856cbac (HEAD -> master) HEAD@{0}: commit: 3rd
c54d388 HEAD@{1}: reset: moving to HEAD~1
2fe670b HEAD@{2}: commit: second commit
c54d388 HEAD@{3}: commit (initial): first commit