从另一个分支复制文件

GitGitBeginner
立即练习

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

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

简介

在 Git 中,分支用于隔离开发工作,而不会影响仓库中的其他分支。有时,你可能需要将文件从另一个分支复制到当前分支。本实验将测试你使用 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-12713{{"`从另一个分支复制文件`"}} end

从另一个分支复制文件

你正在处理一个位于名为 https://github.com/labex-labs/git-playground.git 的 Git 仓库中的项目。你有两个分支,分别名为 feature-1feature-2。你需要将 hello.txt 文件从 feature-1 分支复制到 feature-2 分支。

  1. 克隆仓库:
git clone https://github.com/labex-labs/git-playground.git
  1. 导航到该目录并配置身份:
cd git-playground
git config --global user.name "你的用户名"
git config --global user.email "你的邮箱"
  1. 创建并切换到 feature-1 分支,创建一个名为 hello.txt 的文本文件,并在其中写入字符串 "hello,world",然后使用消息 "添加 hello.txt" 提交该文件:
git checkout -b feature-1
echo "hello,world" > hello.txt
git add.
git commit -m "添加 hello.txt"
  1. 在切换到 master 分支后,创建并切换到 feature-2 分支:
git checkout master
git checkout -b feature-2
  1. hello.txt 文件从 feature-1 分支复制到 feature-2 分支,并使用提交消息 "复制 hello.txt" 提交:
git checkout feature-1 hello.txt
git commit -am "复制 hello.txt"
  1. 验证 hello.txt 文件是否已复制到 feature-2 分支:
ll

你应该在 feature-2 分支的文件列表中看到 hello.txt 文件:

-rw-r--r-- 1 labex labex 15 Jul 12 22:43 file1.txt
-rw-r--r-- 1 labex labex 15 Jul 12 22:43 file2.txt
-rw-r--r-- 1 labex labex 12 Jul 12 22:50 hello.txt
-rw-r--r-- 1 labex labex 32 Jul 12 22:43 README.md

总结

将文件从另一个分支复制到当前分支是一个有用的 Git 命令,它允许你重用其他分支中的代码而不影响当前分支。通过完成本实验,你已经学会了如何使用 Git 从另一个分支复制文件。

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