'Copy changes from one branch to another

I have a branch named BranchA from master. I have some changes in BranchA (I am not going to merge changes from BranchA to master).

Now I have created another branch from master named BranchB.

How can I copy the changes from BranchA to BranchB?

git


Solution 1:[1]

git checkout BranchB
git merge BranchA

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

Solution 2:[2]

Instead of merge, as others suggested, you can rebase one branch onto another:

git checkout BranchB
git rebase BranchA

This takes BranchB and rebases it onto BranchA, which effectively looks like BranchB was branched from BranchA, not master.

Solution 3:[3]

This is 2 step process

  • git checkout BranchB ( destination branch is BranchB, so we need the head on this branch)
  • git merge BranchA (it will merge BranchB with BranchA. Here you have merged code in branch B)

If you want to push your branch code to remote repo then do

  • git push origin master (it will push your BranchB code to remote repo)

Solution 4:[4]

Copy content of BranchA into BranchB

git checkout BranchA
git pull origin BranchB
git push -u origin BranchA

Solution 5:[5]

For me the solution was - stash the current changes in the branch and then switch branches and then apply that stash to that branch.

Solution 6:[6]

Merge the changes from BranchA to BranchB. When you are on BranchB execute git merge BranchA

Solution 7:[7]

If you are using tortoise git.

please follow the below steps.

  1. Checkout BranchB
  2. Open project folder, go to TortoiseGit --> Fetch
  3. In the pull screen, Change the remote branch BranchA and click ok.
  4. Then right-click again, go to TortoiseGit --> Push.

Now your changes moved from BranchA to BranchB

Solution 8:[8]

Simplified solution using git switch

if you have git 2.23 or above you can use git switch command to do the same since git checkout command used for a lot of things which is confusing sometime


// This command will switch(go) to BranchB
// use flag -c if you haven't created this branch yet 
git switch BranchB 


// git merge combines sequences of commits from BranchA to the 
// current branch (which is BranchB)
git merge BranchA

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkrieger1
Solution 2 Archie
Solution 3 TULSI JAIN
Solution 4 Pankaj Singh
Solution 5 ioopl
Solution 6 C1sc0
Solution 7
Solution 8