如何通过实验理解Git工作区与暂存区的过程?

摘要:做个小实验,帮你理解 Git 工作区与暂存区 Git 很重要,本文将通过实验的方式,带你理解 Git 的工作区、暂存区以及相关命令的使用。 1. 什么是工作区和暂存区? 在 Git 中,工作区和暂存区是两个核心概念: 工作区:这是你在本地仓
做个小实验,帮你理解 Git 工作区与暂存区 Git 很重要,本文将通过实验的方式,带你理解 Git 的工作区、暂存区以及相关命令的使用。 1. 什么是工作区和暂存区? 在 Git 中,工作区和暂存区是两个核心概念: 工作区:这是你在本地仓库中实际看到的文件和目录。你可以在工作区中进行文件的新增、修改和删除操作。 暂存区:Git 用来准备下一次提交的区域。通过 git add​ 命令,你可以将工作区中的变更添加到暂存区,暂存区中的内容会作为下一次提交的内容。 2. 实验步骤 实验目标 通过实际操作,理解 Git 的工作区、暂存区以及相关命令的使用。 实验环境 Git 已安装并配置完成 一个本地 Git 仓库 步骤 1:在工作区进行修改 打开本地 Git 仓库,创建一个新文件 test.txt​,并在文件中写入一些内容。 echo "Hello, Git!" > test.txt 修改一个已存在的文件,例如 README.md​,添加一些内容。 步骤 2:使用 git status​ 查看状态 运行 git status​ 命令,查看当前工作区和暂存区的状态: git status 为了简化操作,我为其定义了别名: git config --global alias.st status 输出结果可能如下: On branch main Untracked files: (use "git add <file>..." to include in what will be committed) test.txt Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: README.md 从输出中可以看到,test.txt​ 是一个未跟踪的文件(Untracked files),​README.md​ 已被修改,但还未添加到暂存区(Changes not staged for commit)。 步骤 3:使用 git add​ 添加到暂存区 将 test.txt​ 和 README.md​ 添加到暂存区: git add test.txt README.md 再次运行 git st​ 查看状态: On branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: test.txt modified: README.md 从输出中可以看到,test.txt​ 和 README.md​ 已被添加到暂存区(Changes to be committed)。 步骤 4:使用 git restore --staged​ 移除暂存区 为了简化操作,我为其定义了别名: git config --global alias.unstage 'restore --staged' 将 README.md​ 从暂存区移除: git unstage README.md 再次运行 git st​ 查看状态: On branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: test.txt Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: README.md 从输出中可以看到,test.txt​ 仍然在暂存区中,README.md​ 已被移出暂存区,恢复到工作区的状态。 3. 实验总结 通过本次实验,希望你理解了 Git 的工作区和暂存区,并掌握了以下命令的使用: ​git status​:查看工作区和暂存区的状态。 ​git add​:将工作区的变更添加到暂存区。
阅读全文