How to Copy Changes From One Branch to Another in Git

John Wachira Feb 02, 2024
  1. Copy Changes From One Branch to Another in Git
  2. Conclusion
How to Copy Changes From One Branch to Another in Git

This article discusses two methods we can use to copy changes from one branch to another in Git.

Copy Changes From One Branch to Another in Git

We are all too familiar with the git merge command. We can use it to merge two branches into one.

This command can also be a method to copy changes from one branch to another. However, we can only use it if we want to copy all changes from a branch.

Suppose we have a Master branch in our repository. From our Master branch, we created a new branch called Dev2.1.

Of course, our new branch will inherit all commits in the Master branch. We will then start developing on our Dev2.1 branch.

To copy all the changes from our Dev2.1 branch to our Master branch, we can merge the two as shown below.

First, we have to checkout to the Master branch.

Command:

$ git checkout Master

Now we can merge Dev2.1 to the Master branch.

Command:

$ git merge Dev2.1

You might get merge conflicts, and you have to manually resolve them to complete the merge.

Suppose we want to copy specific changes to the Master branch. We will make some commits in our Dev2.1 branch so that it is ahead of our Master branch and will attempt to copy one commit.

Here is a comparison between our branches.

Comparison between branches

From the output above, our Dev2.1 is ahead of Master by two commits. Let’s assume we only want to copy changes introduced by the Python Scripts commit from our Dev2.1 branch to our Master branch.

To copy the changes, we use the git cherry-pick command with the SHA-1 of our Python Scripts command, as shown below.

Let’s switch to our master branch:

$ git checkout Master

To copy the changes:

$ git cherry-pick 2521a66

Output:

Use git cherry-pick command to copy changes from the Python Script commit to the master branch

We can see that git has copied the changes from the Python Scripts commit to the Master branch. This commit should be visible if we run the git log command.

Command:

$ git log --oneline

Output:

Shows list of the commits made to a repository

Conclusion

You can copy changes from one branch to another using the git merge and git cherry-pick commands. You can specify the changes with the git cherry-pick command while the git merge command copies all the changes.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Branch