分支之间的差异

GitGitBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

Git 是一个流行的版本控制系统,它允许开发者高效地管理他们的代码库。Git 的一个基本特性是创建和管理分支的能力。分支允许开发者同时处理不同的功能或修复 bug,而不会相互干扰。然而,在某些时候,你可能需要比较两个分支之间的差异。在这个实验中,你将学习如何使用 Git 查看两个分支之间的差异。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BranchManagementGroup(["`Branch Management`"]) git/BranchManagementGroup -.-> git/branch("`Handle Branches`") subgraph Lab Skills git/branch -.-> lab-12727{{"`分支之间的差异`"}} end

分支之间的差异

你一直在和团队一起处理一个项目,并且创建了一个名为 feature-1 的分支来处理一项新功能。你的同事也创建了一个名为 feature-2 的分支来处理另一项不同的功能。你想要比较这两个分支之间的更改,看看添加了什么、修改了什么或删除了什么。你该如何查看这两个分支之间的差异呢?

假设你的 GitHub 账户从 https://github.com/labex-labs/git-playground.git 克隆了一个名为 git-playground 的仓库。请按照以下步骤操作:

  1. 使用命令 cd git-playground 切换到仓库目录。
  2. 使用命令 git config --global user.name "你的名字"git config --global user.email "你的邮箱地址" 在这个环境中配置你的 GitHub 账户。
  3. 使用命令 git checkout -b feature-1 创建并切换到 feature-1 分支,在 README.md 文件中添加 "hello",将其添加到暂存区并提交,提交消息为 "Add new content to README.md",使用命令 echo "hello" >> README.md git add.git commit -am "Add new content to README.md"
  4. 切换回 master 分支。
  5. 使用命令 git checkout -b feature-2 创建并切换到 feature-2 分支,在 index.html 文件中添加 "world",将其添加到暂存区并提交,提交消息为 "Update index.html file",使用命令 echo "world" > index.htmgit add.git commit -am "Update index.html file"
  6. 使用命令 git diff feature-1..feature-2 查看这两个分支之间的差异。

输出应该显示 feature-1feature-2 分支之间的差异。这展示了最终结果的样子:

diff --git a/README.md b/README.md
index b66215f..0164284 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,2 @@
## git-playground
Git Playground
-hello
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..cc628cc
--- /dev/null
+++ b/index.html
@@ -0,0 +1 @@
+world

总结

在这个实验中,你已经学会了如何使用 Git 查看两个分支之间的差异。通过使用 git diff 命令,并在两个分支名之间用两个点隔开,你可以比较这两个分支之间的更改。当你想要将一个分支的更改合并到另一个分支,或者想要查看两个分支之间修改了什么时,这个功能非常有用。

您可能感兴趣的其他 Git 教程