Introduction
🧑💻 New to Git or LabEx? We recommend starting with the Quick Start with Git course.
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.
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.
- Clone the repository:
git clone https://github.com/labex-labs/git-playground.git
- 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"
- Create and switch to
feature-1branch and create a text file namedhello.txtand 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"
- Create and switch to
feature-2branch after switching tomasterbranch:
git checkout master
git checkout -b feature-2
- Copy the
hello.txtfile from thefeature-1branch to thefeature-2branch and commit it with the commit message "copy hello.txt":
git checkout feature-1 hello.txt
git commit -am "copy hello.txt"
- Verify that the
hello.txtfile has been copied tofeature-2branch:
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.