Git

How to Copy the Content of a Branch to a New Local Branch?

On Git, developers usually encounter situations where they have worked on the Git local branch and pushed all the added changes to the GitHub hosting service. After that, it is required to revert the modifications on that particular branch and add new code related to the development project. On the other hand, they don’t want to lose existing data of the particular branch. In this situation, they need to copy the content of one branch to another.

This guide will explain the procedure of copying the content of one branch to a new local branch.

How to Copy the Content of One Local Branch to a New Branch?

Try out the below-provided steps to copy the content of a branch to a new local branch:

  • Navigate to the Git desired directory.
  • Check the list of content.
  • View all the existing local branches.
  • Run the “$ git checkout <new-branch-name> <working-branch-name>” command.

Let’s check out the practical demonstration of the above-stated instructions.

Step 1: Move to Local Repository

First, go to the Git repository by executing the following command:

$ cd "C:\Users\nazma\Git\Test_12"

Step 2: View List of Content

Now, run the “ls” command to display the repository’s existing content:

$ ls

Step 3: Check Local Branches List

Next, check all Git local branches by utilizing the below-stated command:

$ git branch

Here, the asterisk “*” symbol beside the “master” branch indicates that it is a current working branch:

Step 4: Create and Checkout to New Local Branch

Then, execute the “git checkout” command along with the “-b” flag, new branch name, and current working branch:

$ git checkout -b gemma master

As a result, all the existing content of the current working branch will be copied to the newly created branch:

Step 5: Verify Copied Content

Lastly, verify the procedure of copying content from the current working branch to the new branch by running the “ls” command:

$ ls

As you can see, the content is copied successfully to the new branch:

That’s all! We have compiled authentic information about copying the content of a branch to a newly created local branch.

Conclusion

To copy the content of a branch to a new local branch, first, move to the Git desired directory and view the list of content. Then, check the existing branches, and execute the “$ git checkout <new-branch-name> <working-branch-name>” command. This guide efficiently explained the method of copying the content of a branch to a new local branch.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.