Copy a File from Another Branch

GitGitBeginner
Practice Now

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

Introduction

In Git, branches are used to isolate development work without affecting other branches in the repository. Sometimes, you may need to copy a file from another branch to the current branch. This lab will test your ability to copy a file from another branch using 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{{"`Copy a File from Another Branch`"}} end

Copy a File from Another Branch

You are working on a project in a Git repository named https://github.com/labex-labs/git-playground.git. You have two branches named feature-1 and feature-2. You need to copy the file hello.txt from feature-1 branch to feature-2 branch.

  1. Clone the repository:
git clone https://github.com/labex-labs/git-playground.git
  1. Navigate to the directory and configure the identity:
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
  1. Create and switch to feature-1 branch and create a text file named hello.txt and write the string "hello,world" to it and commit the file with the message "add hello.txt":
git checkout -b feature-1
echo "hello,world" > hello.txt
git add .
git commit -m "add hello.txt"
  1. Create and switch to feature-2 branch after switching to master branch:
git checkout master
git checkout -b feature-2
  1. Copy the hello.txt file from the feature-1 branch to the feature-2 branch and commit it with the commit message "copy hello.txt":
git checkout feature-1 hello.txt
git commit -am "copy hello.txt"
  1. Verify that the hello.txt file has been copied to feature-2 branch:
ll

You should see the hello.txt file in the list of files in the feature-2 branch:

-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

Summary

Copying a file from another branch to the current branch is a useful Git command that allows you to reuse code from other branches without affecting the current branch. By completing this lab, you have learned how to copy a file from another branch using Git.

Other Git Tutorials you may like